Coverage Report

Created: 2024-07-08 07:40

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90.9 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
442
                            - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
443
                            - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
444
 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
445
 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
446
 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
447
 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
448
 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
449
 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
450
 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
451
                            - old: CaptureKeyboardFromApp(bool)
452
                            - new: SetNextFrameWantCaptureKeyboard(bool)
453
                            - old: CaptureMouseFromApp(bool)
454
                            - new: SetNextFrameWantCaptureMouse(bool)
455
 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
456
                       - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
457
                       - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
458
                            - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
459
                            - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
460
                       - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
461
                            - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
462
                            - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
463
                            - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
464
                            - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
465
                         for various reasons those changes makes sense. They are being made because making some of those API public.
466
                         only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
467
 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
468
                           - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
469
                           - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
470
 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
471
                           - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
472
                           - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
473
 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
474
 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
475
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
476
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
477
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
478
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
479
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
480
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
481
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
482
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
483
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
484
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
485
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
486
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
487
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
488
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
489
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
490
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
491
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
492
                           - old: BeginChild("Name", size, true)
493
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
494
                           - old: BeginChild("Name", size, false)
495
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
496
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
497
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
498
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
499
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
500
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
501
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
502
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
503
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
504
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
505
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
506
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
507
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
508
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
509
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
510
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
511
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
512
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
513
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
514
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
515
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
516
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
517
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
518
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
519
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
520
                           - ListBoxFooter()  -> use EndListBox()
521
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
522
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
523
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
524
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
525
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
526
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
527
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
528
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
529
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
530
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
531
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
532
                         it has been frequently requested by people to use our own. We had an opt-in define which was
533
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
534
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
535
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
536
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
537
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
538
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
539
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
540
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
541
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
542
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
543
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
544
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
545
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
546
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
547
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
548
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
549
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
550
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
551
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
552
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
553
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
554
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
555
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
556
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
557
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
558
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
559
                         - previously this would make the window content size ~200x200:
560
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
561
                         - instead, please submit an item:
562
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
563
                         - alternative:
564
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
565
                         - content size is now only extended when submitting an item!
566
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
567
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
568
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
569
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
570
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
571
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
572
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
573
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
574
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
575
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
576
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
577
                        - Official backends from 1.87+                  -> no issue.
578
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
579
                        - Custom backends not writing to io.NavInputs[] -> no issue.
580
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
581
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
582
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
583
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
584
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
585
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
586
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
587
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
588
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
589
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
590
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
591
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
592
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
593
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
594
                       read https://github.com/ocornut/imgui/issues/4921 for details.
595
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
596
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
597
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
598
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
599
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
600
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
601
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
602
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
603
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
604
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
605
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
606
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
607
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
608
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
609
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
610
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
611
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
612
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
613
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
614
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
615
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
616
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
617
                        - if you are using official backends from the source tree: you have nothing to do.
618
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
619
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
620
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
621
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
622
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
623
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
624
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
625
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
626
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
627
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
628
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
629
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
630
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
631
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
632
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
633
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
634
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
635
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
636
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
637
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
638
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
639
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
640
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
641
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
642
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
643
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
644
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
645
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
646
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
647
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
648
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
649
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
650
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
651
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
652
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
653
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
654
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
655
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
656
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
657
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
658
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
659
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
660
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
661
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
662
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
663
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
664
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
665
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
666
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
667
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
668
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
669
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
670
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
671
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
672
                       - if you omitted the 'power' parameter (likely!), you are not affected.
673
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
674
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
675
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
676
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
677
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
678
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
679
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
680
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
681
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
682
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
683
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
684
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
685
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
686
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
687
                       - ShowTestWindow()                    -> use ShowDemoWindow()
688
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
689
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
690
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
691
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
692
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
693
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
694
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
695
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
696
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
697
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
698
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
699
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
700
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
701
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
702
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
703
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
704
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
705
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
706
                       - ImFont::Glyph                       -> use ImFontGlyph
707
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
708
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
709
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
710
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
711
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
712
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
713
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
714
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
715
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
716
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
717
                       Please reach out if you are affected.
718
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
719
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
720
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
721
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
722
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
723
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
724
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
725
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
726
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
727
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
728
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
729
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
730
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
731
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
732
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
733
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
734
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
735
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
736
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
737
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
738
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
739
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
740
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
741
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
742
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
743
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
744
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
745
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
746
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
747
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
748
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
749
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
750
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
751
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
752
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
753
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
754
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
755
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
756
                       consistent with other functions. Kept redirection functions (will obsolete).
757
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
758
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
759
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
760
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
761
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
762
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
763
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
764
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
765
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
766
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
767
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
768
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
769
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
770
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
771
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
772
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
773
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
774
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
775
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
776
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
777
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
778
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
779
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
780
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
781
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
782
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
783
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
784
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
785
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
786
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
787
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
788
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
789
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
790
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
791
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
792
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
793
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
794
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
795
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
796
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
797
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
798
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
799
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
800
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
801
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
802
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
803
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
804
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
805
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
806
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
807
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
808
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
809
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
810
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
811
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
812
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
813
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
814
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
815
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
816
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
817
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
818
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
819
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
820
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
821
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
822
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
823
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
824
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
825
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
826
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
827
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
828
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
829
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
830
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
831
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
832
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
833
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
834
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
835
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
836
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
837
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
838
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
839
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
840
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
841
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
842
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
843
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
844
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
845
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
846
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
847
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
848
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
849
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
850
                     - the signature of the io.RenderDrawListsFn handler has changed!
851
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
852
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
853
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
854
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
855
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
856
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
857
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
858
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
859
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
860
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
861
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
862
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
863
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
864
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
865
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
866
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
867
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
868
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
869
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
870
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
871
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
872
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
873
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
874
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
875
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
876
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
877
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
878
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
879
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
880
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
881
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
882
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
883
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
884
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
885
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
886
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
887
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
888
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
889
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
890
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
891
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
892
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
893
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
894
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
895
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
896
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
897
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
898
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
899
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
900
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
901
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
902
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
903
904
905
 FREQUENTLY ASKED QUESTIONS (FAQ)
906
 ================================
907
908
 Read all answers online:
909
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
910
 Read all answers locally (with a text editor or ideally a Markdown viewer):
911
   docs/FAQ.md
912
 Some answers are copied down here to facilitate searching in code.
913
914
 Q&A: Basics
915
 ===========
916
917
 Q: Where is the documentation?
918
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
919
    - Run the examples/ applications and explore them.
920
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
921
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
922
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
923
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
924
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
925
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
926
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
927
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
928
    - Your programming IDE is your friend, find the type or function declaration to find comments
929
      associated with it.
930
931
 Q: What is this library called?
932
 Q: Which version should I get?
933
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
934
 >> See https://www.dearimgui.com/faq for details.
935
936
 Q&A: Integration
937
 ================
938
939
 Q: How to get started?
940
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
941
942
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
943
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
944
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
945
946
 Q. How can I enable keyboard or gamepad controls?
947
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
948
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
949
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
950
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
951
 >> See https://www.dearimgui.com/faq
952
953
 Q&A: Usage
954
 ----------
955
956
 Q: About the ID Stack system..
957
   - Why is my widget not reacting when I click on it?
958
   - How can I have widgets with an empty label?
959
   - How can I have multiple widgets with the same label?
960
   - How can I have multiple windows with the same label?
961
 Q: How can I display an image? What is ImTextureID, how does it work?
962
 Q: How can I use my own math types instead of ImVec2?
963
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
964
 Q: How can I display custom shapes? (using low-level ImDrawList API)
965
 >> See https://www.dearimgui.com/faq
966
967
 Q&A: Fonts, Text
968
 ================
969
970
 Q: How should I handle DPI in my application?
971
 Q: How can I load a different font than the default?
972
 Q: How can I easily use icons in my application?
973
 Q: How can I load multiple fonts?
974
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
975
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
976
977
 Q&A: Concerns
978
 =============
979
980
 Q: Who uses Dear ImGui?
981
 Q: Can you create elaborate/serious tools with Dear ImGui?
982
 Q: Can you reskin the look of Dear ImGui?
983
 Q: Why using C++ (as opposed to C)?
984
 >> See https://www.dearimgui.com/faq
985
986
 Q&A: Community
987
 ==============
988
989
 Q: How can I help?
990
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
991
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
992
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
993
      >>> See https://github.com/ocornut/imgui/wiki/Funding
994
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
995
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
996
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
997
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
998
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
999
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1000
1001
*/
1002
1003
//-------------------------------------------------------------------------
1004
// [SECTION] INCLUDES
1005
//-------------------------------------------------------------------------
1006
1007
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1008
#define _CRT_SECURE_NO_WARNINGS
1009
#endif
1010
1011
#ifndef IMGUI_DEFINE_MATH_OPERATORS
1012
#define IMGUI_DEFINE_MATH_OPERATORS
1013
#endif
1014
1015
#include "imgui.h"
1016
#ifndef IMGUI_DISABLE
1017
#include "imgui_internal.h"
1018
1019
// System includes
1020
#include <stdio.h>      // vsnprintf, sscanf, printf
1021
#include <stdint.h>     // intptr_t
1022
1023
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1024
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1025
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1026
#endif
1027
1028
// [Windows] OS specific includes (optional)
1029
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1030
#define IMGUI_DISABLE_WIN32_FUNCTIONS
1031
#endif
1032
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1033
#ifndef WIN32_LEAN_AND_MEAN
1034
#define WIN32_LEAN_AND_MEAN
1035
#endif
1036
#ifndef NOMINMAX
1037
#define NOMINMAX
1038
#endif
1039
#ifndef __MINGW32__
1040
#include <Windows.h>        // _wfopen, OpenClipboard
1041
#else
1042
#include <windows.h>
1043
#endif
1044
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1045
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1046
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1047
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1048
#endif
1049
#endif
1050
1051
// [Apple] OS specific includes
1052
#if defined(__APPLE__)
1053
#include <TargetConditionals.h>
1054
#endif
1055
1056
// Visual Studio warnings
1057
#ifdef _MSC_VER
1058
#pragma warning (disable: 4127)             // condition expression is constant
1059
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1060
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1061
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1062
#endif
1063
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1064
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1065
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1066
#endif
1067
1068
// Clang/GCC warnings with -Weverything
1069
#if defined(__clang__)
1070
#if __has_warning("-Wunknown-warning-option")
1071
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1072
#endif
1073
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1074
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1075
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1076
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1077
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1078
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1079
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1080
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1081
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1082
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1083
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1084
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1085
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1086
#elif defined(__GNUC__)
1087
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1088
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1089
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1090
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1091
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1092
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1093
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1094
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1095
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1096
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1097
#endif
1098
1099
// Debug options
1100
287k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1101
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1102
1103
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1104
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1105
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1106
1107
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1108
1109
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1110
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1111
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1112
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1113
1114
// Tooltip offset
1115
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1116
1117
// Docking
1118
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1119
1120
//-------------------------------------------------------------------------
1121
// [SECTION] FORWARD DECLARATIONS
1122
//-------------------------------------------------------------------------
1123
1124
static void             SetCurrentWindow(ImGuiWindow* window);
1125
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1126
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1127
1128
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1129
1130
// Settings
1131
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1132
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1133
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1134
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1135
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1136
1137
// Platform Dependents default implementation for IO functions
1138
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1139
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1140
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1141
1142
namespace ImGui
1143
{
1144
// Item
1145
static void             ItemHandleShortcut(ImGuiID id);
1146
1147
// Navigation
1148
static void             NavUpdate();
1149
static void             NavUpdateWindowing();
1150
static void             NavUpdateWindowingOverlay();
1151
static void             NavUpdateCancelRequest();
1152
static void             NavUpdateCreateMoveRequest();
1153
static void             NavUpdateCreateTabbingRequest();
1154
static float            NavUpdatePageUpPageDown();
1155
static inline void      NavUpdateAnyRequestFlag();
1156
static void             NavUpdateCreateWrappingRequest();
1157
static void             NavEndFrame();
1158
static bool             NavScoreItem(ImGuiNavItemData* result);
1159
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1160
static void             NavProcessItem();
1161
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1162
static ImVec2           NavCalcPreferredRefPos();
1163
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1164
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1165
static void             NavRestoreLayer(ImGuiNavLayer layer);
1166
static int              FindWindowFocusIndex(ImGuiWindow* window);
1167
1168
// Error Checking and Debug Tools
1169
static void             ErrorCheckNewFrameSanityChecks();
1170
static void             ErrorCheckEndFrameSanityChecks();
1171
static void             UpdateDebugToolItemPicker();
1172
static void             UpdateDebugToolStackQueries();
1173
static void             UpdateDebugToolFlashStyleColor();
1174
1175
// Inputs
1176
static void             UpdateKeyboardInputs();
1177
static void             UpdateMouseInputs();
1178
static void             UpdateMouseWheel();
1179
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1180
1181
// Misc
1182
static void             UpdateSettings();
1183
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1184
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1185
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1186
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1187
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1188
static void             RenderDimmedBackgrounds();
1189
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1190
1191
// Viewports
1192
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1193
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1194
static void             DestroyViewport(ImGuiViewportP* viewport);
1195
static void             UpdateViewportsNewFrame();
1196
static void             UpdateViewportsEndFrame();
1197
static void             WindowSelectViewport(ImGuiWindow* window);
1198
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1199
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1200
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1201
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1202
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1203
static int              FindPlatformMonitorForRect(const ImRect& r);
1204
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1205
1206
}
1207
1208
//-----------------------------------------------------------------------------
1209
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1210
//-----------------------------------------------------------------------------
1211
1212
// DLL users:
1213
// - Heaps and globals are not shared across DLL boundaries!
1214
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1215
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1216
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1217
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1218
1219
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1220
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1221
//   Change to a different context by calling ImGui::SetCurrentContext().
1222
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1223
//   If you want thread-safety to allow N threads to access N different contexts:
1224
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1225
//         struct ImGuiContext;
1226
//         extern thread_local ImGuiContext* MyImGuiTLS;
1227
//         #define GImGui MyImGuiTLS
1228
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1229
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1230
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1231
// - DLL users: read comments above.
1232
#ifndef GImGui
1233
ImGuiContext*   GImGui = NULL;
1234
#endif
1235
1236
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1237
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1238
// - DLL users: read comments above.
1239
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1240
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1241
1.18k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1242
#else
1243
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1244
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1245
#endif
1246
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1247
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1248
static void*                GImAllocatorUserData = NULL;
1249
1250
//-----------------------------------------------------------------------------
1251
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1252
//-----------------------------------------------------------------------------
1253
1254
ImGuiStyle::ImGuiStyle()
1255
1
{
1256
1
    Alpha                       = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1257
1
    DisabledAlpha               = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1258
1
    WindowPadding               = ImVec2(8,8);      // Padding within a window
1259
1
    WindowRounding              = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1260
1
    WindowBorderSize            = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1261
1
    WindowMinSize               = ImVec2(32,32);    // Minimum window size
1262
1
    WindowTitleAlign            = ImVec2(0.0f,0.5f);// Alignment for title bar text
1263
1
    WindowMenuButtonPosition    = ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1264
1
    ChildRounding               = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1265
1
    ChildBorderSize             = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1266
1
    PopupRounding               = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1267
1
    PopupBorderSize             = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1268
1
    FramePadding                = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1269
1
    FrameRounding               = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1270
1
    FrameBorderSize             = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1271
1
    ItemSpacing                 = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1272
1
    ItemInnerSpacing            = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1273
1
    CellPadding                 = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1274
1
    TouchExtraPadding           = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1275
1
    IndentSpacing               = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1276
1
    ColumnsMinSpacing           = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1277
1
    ScrollbarSize               = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1278
1
    ScrollbarRounding           = 9.0f;             // Radius of grab corners rounding for scrollbar
1279
1
    GrabMinSize                 = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1280
1
    GrabRounding                = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1281
1
    LogSliderDeadzone           = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1282
1
    TabRounding                 = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1283
1
    TabBorderSize               = 0.0f;             // Thickness of border around tabs.
1284
1
    TabMinWidthForCloseButton   = 0.0f;             // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1285
1
    TabBarBorderSize            = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1286
1
    TableAngledHeadersAngle     = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1287
1
    TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1288
1
    ColorButtonPosition         = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1289
1
    ButtonTextAlign             = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1290
1
    SelectableTextAlign         = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1291
1
    SeparatorTextBorderSize     = 3.0f;             // Thickkness of border in SeparatorText()
1292
1
    SeparatorTextAlign          = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1293
1
    SeparatorTextPadding        = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1294
1
    DisplayWindowPadding        = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1295
1
    DisplaySafeAreaPadding      = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1296
1
    DockingSeparatorSize        = 2.0f;             // Thickness of resizing border between docked windows
1297
1
    MouseCursorScale            = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1298
1
    AntiAliasedLines            = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1299
1
    AntiAliasedLinesUseTex      = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1300
1
    AntiAliasedFill             = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1301
1
    CurveTessellationTol        = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1302
1
    CircleTessellationMaxError  = 0.30f;            // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1303
1304
    // Behaviors
1305
1
    HoverStationaryDelay        = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1306
1
    HoverDelayShort             = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1307
1
    HoverDelayNormal            = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1308
1
    HoverFlagsForTooltipMouse   = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1309
1
    HoverFlagsForTooltipNav     = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1310
1311
    // Default theme
1312
1
    ImGui::StyleColorsDark(this);
1313
1
}
1314
1315
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1316
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1317
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1318
0
{
1319
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1320
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1321
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1322
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1323
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1324
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1325
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1326
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1327
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1328
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1329
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1330
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1331
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1332
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1333
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1334
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1335
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1336
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1337
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1338
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1339
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1340
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1341
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1342
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1343
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1344
0
}
1345
1346
ImGuiIO::ImGuiIO()
1347
1
{
1348
    // Most fields are initialized with zero
1349
1
    memset(this, 0, sizeof(*this));
1350
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1351
1352
    // Settings
1353
1
    ConfigFlags = ImGuiConfigFlags_None;
1354
1
    BackendFlags = ImGuiBackendFlags_None;
1355
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1356
1
    DeltaTime = 1.0f / 60.0f;
1357
1
    IniSavingRate = 5.0f;
1358
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1359
1
    LogFilename = "imgui_log.txt";
1360
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1361
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1362
        KeyMap[i] = -1;
1363
#endif
1364
1
    UserData = NULL;
1365
1366
1
    Fonts = NULL;
1367
1
    FontGlobalScale = 1.0f;
1368
1
    FontDefault = NULL;
1369
1
    FontAllowUserScaling = false;
1370
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1371
1372
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1373
1
    ConfigDockingNoSplit = false;
1374
1
    ConfigDockingWithShift = false;
1375
1
    ConfigDockingAlwaysTabBar = false;
1376
1
    ConfigDockingTransparentPayload = false;
1377
1378
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1379
1
    ConfigViewportsNoAutoMerge = false;
1380
1
    ConfigViewportsNoTaskBarIcon = false;
1381
1
    ConfigViewportsNoDecoration = true;
1382
1
    ConfigViewportsNoDefaultParent = false;
1383
1384
    // Miscellaneous options
1385
1
    MouseDrawCursor = false;
1386
#ifdef __APPLE__
1387
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1388
#else
1389
1
    ConfigMacOSXBehaviors = false;
1390
1
#endif
1391
1
    ConfigInputTrickleEventQueue = true;
1392
1
    ConfigInputTextCursorBlink = true;
1393
1
    ConfigInputTextEnterKeepActive = false;
1394
1
    ConfigDragClickToInputText = false;
1395
1
    ConfigWindowsResizeFromEdges = true;
1396
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1397
1
    ConfigMemoryCompactTimer = 60.0f;
1398
1
    ConfigDebugBeginReturnValueOnce = false;
1399
1
    ConfigDebugBeginReturnValueLoop = false;
1400
1401
    // Inputs Behaviors
1402
1
    MouseDoubleClickTime = 0.30f;
1403
1
    MouseDoubleClickMaxDist = 6.0f;
1404
1
    MouseDragThreshold = 6.0f;
1405
1
    KeyRepeatDelay = 0.275f;
1406
1
    KeyRepeatRate = 0.050f;
1407
1408
    // Platform Functions
1409
    // Note: Initialize() will setup default clipboard/ime handlers.
1410
1
    BackendPlatformName = BackendRendererName = NULL;
1411
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1412
1
    PlatformLocaleDecimalPoint = '.';
1413
1414
    // Input (NB: we already have memset zero the entire structure!)
1415
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1416
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1417
1
    MouseSource = ImGuiMouseSource_Mouse;
1418
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1419
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1420
1
    AppAcceptingEvents = true;
1421
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1422
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1423
1
}
1424
1425
// Pass in translated ASCII characters for text input.
1426
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1427
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1428
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1429
void ImGuiIO::AddInputCharacter(unsigned int c)
1430
10.2k
{
1431
10.2k
    IM_ASSERT(Ctx != NULL);
1432
10.2k
    ImGuiContext& g = *Ctx;
1433
10.2k
    if (c == 0 || !AppAcceptingEvents)
1434
2.59k
        return;
1435
1436
7.69k
    ImGuiInputEvent e;
1437
7.69k
    e.Type = ImGuiInputEventType_Text;
1438
7.69k
    e.Source = ImGuiInputSource_Keyboard;
1439
7.69k
    e.EventId = g.InputEventsNextEventId++;
1440
7.69k
    e.Text.Char = c;
1441
7.69k
    g.InputEventsQueue.push_back(e);
1442
7.69k
}
1443
1444
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1445
// we should save the high surrogate.
1446
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1447
2.35k
{
1448
2.35k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1449
174
        return;
1450
1451
2.18k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1452
834
    {
1453
834
        if (InputQueueSurrogate != 0)
1454
251
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1455
834
        InputQueueSurrogate = c;
1456
834
        return;
1457
834
    }
1458
1459
1.34k
    ImWchar cp = c;
1460
1.34k
    if (InputQueueSurrogate != 0)
1461
565
    {
1462
565
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1463
531
        {
1464
531
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1465
531
        }
1466
34
        else
1467
34
        {
1468
34
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1469
34
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1470
#else
1471
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1472
#endif
1473
34
        }
1474
1475
565
        InputQueueSurrogate = 0;
1476
565
    }
1477
1.34k
    AddInputCharacter((unsigned)cp);
1478
1.34k
}
1479
1480
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1481
61
{
1482
61
    if (!AppAcceptingEvents)
1483
0
        return;
1484
61
    while (*utf8_chars != 0)
1485
0
    {
1486
0
        unsigned int c = 0;
1487
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1488
0
        AddInputCharacter(c);
1489
0
    }
1490
61
}
1491
1492
// Clear all incoming events.
1493
void ImGuiIO::ClearEventsQueue()
1494
0
{
1495
0
    IM_ASSERT(Ctx != NULL);
1496
0
    ImGuiContext& g = *Ctx;
1497
0
    g.InputEventsQueue.clear();
1498
0
}
1499
1500
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1501
void ImGuiIO::ClearInputKeys()
1502
19.1k
{
1503
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1504
    memset(KeysDown, 0, sizeof(KeysDown));
1505
#endif
1506
2.97M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1507
2.95M
    {
1508
2.95M
        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1509
134k
            continue;
1510
2.82M
        KeysData[n].Down             = false;
1511
2.82M
        KeysData[n].DownDuration     = -1.0f;
1512
2.82M
        KeysData[n].DownDurationPrev = -1.0f;
1513
2.82M
    }
1514
19.1k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1515
19.1k
    KeyMods = ImGuiMod_None;
1516
19.1k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1517
19.1k
}
1518
1519
void ImGuiIO::ClearInputMouse()
1520
5.34k
{
1521
42.7k
    for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1522
37.3k
    {
1523
37.3k
        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1524
37.3k
        key_data->Down = false;
1525
37.3k
        key_data->DownDuration = -1.0f;
1526
37.3k
        key_data->DownDurationPrev = -1.0f;
1527
37.3k
    }
1528
5.34k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1529
32.0k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1530
26.7k
    {
1531
26.7k
        MouseDown[n] = false;
1532
26.7k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1533
26.7k
    }
1534
5.34k
    MouseWheel = MouseWheelH = 0.0f;
1535
5.34k
}
1536
1537
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1538
// Current frame character buffer is now also cleared by ClearInputKeys().
1539
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1540
void ImGuiIO::ClearInputCharacters()
1541
{
1542
    InputQueueCharacters.resize(0);
1543
}
1544
#endif
1545
1546
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1547
53.5k
{
1548
53.5k
    ImGuiContext& g = *ctx;
1549
86.6k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1550
49.1k
    {
1551
49.1k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1552
49.1k
        if (e->Type != type)
1553
27.5k
            continue;
1554
21.5k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1555
2.49k
            continue;
1556
19.0k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1557
2.99k
            continue;
1558
16.0k
        return e;
1559
19.0k
    }
1560
37.4k
    return NULL;
1561
53.5k
}
1562
1563
// Queue a new key down/up event.
1564
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1565
// - bool down:          Is the key down? use false to signify a key release.
1566
// - float analog_value: 0.0f..1.0f
1567
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1568
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1569
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1570
18.0k
{
1571
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1572
18.0k
    IM_ASSERT(Ctx != NULL);
1573
18.0k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1574
0
        return;
1575
18.0k
    ImGuiContext& g = *Ctx;
1576
18.0k
    IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1577
18.0k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1578
1579
    // MacOS: swap Cmd(Super) and Ctrl
1580
18.0k
    if (g.IO.ConfigMacOSXBehaviors)
1581
0
    {
1582
0
        if (key == ImGuiMod_Super)          { key = ImGuiMod_Ctrl; }
1583
0
        else if (key == ImGuiMod_Ctrl)      { key = ImGuiMod_Super; }
1584
0
        else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1585
0
        else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1586
0
        else if (key == ImGuiKey_LeftCtrl)  { key = ImGuiKey_LeftSuper; }
1587
0
        else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1588
0
    }
1589
1590
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1591
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1592
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1593
    if (BackendUsingLegacyKeyArrays == -1)
1594
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1595
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1596
    BackendUsingLegacyKeyArrays = 0;
1597
#endif
1598
18.0k
    if (ImGui::IsGamepadKey(key))
1599
95
        BackendUsingLegacyNavInputArray = false;
1600
1601
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1602
18.0k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1603
18.0k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1604
18.0k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1605
18.0k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1606
18.0k
    if (latest_key_down == down && latest_key_analog == analog_value)
1607
3.15k
        return;
1608
1609
    // Add event
1610
14.8k
    ImGuiInputEvent e;
1611
14.8k
    e.Type = ImGuiInputEventType_Key;
1612
14.8k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1613
14.8k
    e.EventId = g.InputEventsNextEventId++;
1614
14.8k
    e.Key.Key = key;
1615
14.8k
    e.Key.Down = down;
1616
14.8k
    e.Key.AnalogValue = analog_value;
1617
14.8k
    g.InputEventsQueue.push_back(e);
1618
14.8k
}
1619
1620
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1621
1.33k
{
1622
1.33k
    if (!AppAcceptingEvents)
1623
0
        return;
1624
1.33k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1625
1.33k
}
1626
1627
// [Optional] Call after AddKeyEvent().
1628
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1629
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1630
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1631
0
{
1632
0
    if (key == ImGuiKey_None)
1633
0
        return;
1634
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1635
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1636
0
    IM_UNUSED(native_keycode);  // Yet unused
1637
0
    IM_UNUSED(native_scancode); // Yet unused
1638
1639
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1640
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1641
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1642
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1643
        return;
1644
    KeyMap[legacy_key] = key;
1645
    KeyMap[key] = legacy_key;
1646
#else
1647
0
    IM_UNUSED(key);
1648
0
    IM_UNUSED(native_legacy_index);
1649
0
#endif
1650
0
}
1651
1652
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1653
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1654
0
{
1655
0
    AppAcceptingEvents = accepting_events;
1656
0
}
1657
1658
// Queue a mouse move event
1659
void ImGuiIO::AddMousePosEvent(float x, float y)
1660
8.56k
{
1661
8.56k
    IM_ASSERT(Ctx != NULL);
1662
8.56k
    ImGuiContext& g = *Ctx;
1663
8.56k
    if (!AppAcceptingEvents)
1664
0
        return;
1665
1666
    // Apply same flooring as UpdateMouseInputs()
1667
8.56k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1668
1669
    // Filter duplicate
1670
8.56k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1671
8.56k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1672
8.56k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1673
1.79k
        return;
1674
1675
6.77k
    ImGuiInputEvent e;
1676
6.77k
    e.Type = ImGuiInputEventType_MousePos;
1677
6.77k
    e.Source = ImGuiInputSource_Mouse;
1678
6.77k
    e.EventId = g.InputEventsNextEventId++;
1679
6.77k
    e.MousePos.PosX = pos.x;
1680
6.77k
    e.MousePos.PosY = pos.y;
1681
6.77k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1682
6.77k
    g.InputEventsQueue.push_back(e);
1683
6.77k
}
1684
1685
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1686
20.0k
{
1687
20.0k
    IM_ASSERT(Ctx != NULL);
1688
20.0k
    ImGuiContext& g = *Ctx;
1689
20.0k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1690
20.0k
    if (!AppAcceptingEvents)
1691
0
        return;
1692
1693
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1694
20.0k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1695
0
    {
1696
        // Order of both statements matterns: this event will still release mouse button 1
1697
0
        mouse_button = 1;
1698
0
        if (!down)
1699
0
            MouseCtrlLeftAsRightClick = false;
1700
0
    }
1701
1702
    // Filter duplicate
1703
20.0k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1704
20.0k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1705
20.0k
    if (latest_button_down == down)
1706
7.40k
        return;
1707
1708
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1709
    // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1710
    // - At this point we want from !down to down, so this is handling the initial press.
1711
12.6k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1712
0
    {
1713
0
        const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1714
0
        if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1715
0
        {
1716
0
            IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1717
0
            MouseCtrlLeftAsRightClick = true;
1718
0
            AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1719
0
            return;
1720
0
        }
1721
0
    }
1722
1723
12.6k
    ImGuiInputEvent e;
1724
12.6k
    e.Type = ImGuiInputEventType_MouseButton;
1725
12.6k
    e.Source = ImGuiInputSource_Mouse;
1726
12.6k
    e.EventId = g.InputEventsNextEventId++;
1727
12.6k
    e.MouseButton.Button = mouse_button;
1728
12.6k
    e.MouseButton.Down = down;
1729
12.6k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1730
12.6k
    g.InputEventsQueue.push_back(e);
1731
12.6k
}
1732
1733
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1734
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1735
5.17k
{
1736
5.17k
    IM_ASSERT(Ctx != NULL);
1737
5.17k
    ImGuiContext& g = *Ctx;
1738
1739
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1740
5.17k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1741
127
        return;
1742
1743
5.05k
    ImGuiInputEvent e;
1744
5.05k
    e.Type = ImGuiInputEventType_MouseWheel;
1745
5.05k
    e.Source = ImGuiInputSource_Mouse;
1746
5.05k
    e.EventId = g.InputEventsNextEventId++;
1747
5.05k
    e.MouseWheel.WheelX = wheel_x;
1748
5.05k
    e.MouseWheel.WheelY = wheel_y;
1749
5.05k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1750
5.05k
    g.InputEventsQueue.push_back(e);
1751
5.05k
}
1752
1753
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1754
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1755
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1756
0
{
1757
0
    IM_ASSERT(Ctx != NULL);
1758
0
    ImGuiContext& g = *Ctx;
1759
0
    g.InputEventsNextMouseSource = source;
1760
0
}
1761
1762
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1763
0
{
1764
0
    IM_ASSERT(Ctx != NULL);
1765
0
    ImGuiContext& g = *Ctx;
1766
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1767
0
    if (!AppAcceptingEvents)
1768
0
        return;
1769
1770
    // Filter duplicate
1771
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1772
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1773
0
    if (latest_viewport_id == viewport_id)
1774
0
        return;
1775
1776
0
    ImGuiInputEvent e;
1777
0
    e.Type = ImGuiInputEventType_MouseViewport;
1778
0
    e.Source = ImGuiInputSource_Mouse;
1779
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1780
0
    g.InputEventsQueue.push_back(e);
1781
0
}
1782
1783
void ImGuiIO::AddFocusEvent(bool focused)
1784
6.94k
{
1785
6.94k
    IM_ASSERT(Ctx != NULL);
1786
6.94k
    ImGuiContext& g = *Ctx;
1787
1788
    // Filter duplicate
1789
6.94k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1790
6.94k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1791
6.94k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1792
1.20k
        return;
1793
1794
5.73k
    ImGuiInputEvent e;
1795
5.73k
    e.Type = ImGuiInputEventType_Focus;
1796
5.73k
    e.EventId = g.InputEventsNextEventId++;
1797
5.73k
    e.AppFocused.Focused = focused;
1798
5.73k
    g.InputEventsQueue.push_back(e);
1799
5.73k
}
1800
1801
//-----------------------------------------------------------------------------
1802
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1803
//-----------------------------------------------------------------------------
1804
1805
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1806
0
{
1807
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1808
0
    ImVec2 p_last = p1;
1809
0
    ImVec2 p_closest;
1810
0
    float p_closest_dist2 = FLT_MAX;
1811
0
    float t_step = 1.0f / (float)num_segments;
1812
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1813
0
    {
1814
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1815
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1816
0
        float dist2 = ImLengthSqr(p - p_line);
1817
0
        if (dist2 < p_closest_dist2)
1818
0
        {
1819
0
            p_closest = p_line;
1820
0
            p_closest_dist2 = dist2;
1821
0
        }
1822
0
        p_last = p_current;
1823
0
    }
1824
0
    return p_closest;
1825
0
}
1826
1827
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1828
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1829
0
{
1830
0
    float dx = x4 - x1;
1831
0
    float dy = y4 - y1;
1832
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1833
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1834
0
    d2 = (d2 >= 0) ? d2 : -d2;
1835
0
    d3 = (d3 >= 0) ? d3 : -d3;
1836
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1837
0
    {
1838
0
        ImVec2 p_current(x4, y4);
1839
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1840
0
        float dist2 = ImLengthSqr(p - p_line);
1841
0
        if (dist2 < p_closest_dist2)
1842
0
        {
1843
0
            p_closest = p_line;
1844
0
            p_closest_dist2 = dist2;
1845
0
        }
1846
0
        p_last = p_current;
1847
0
    }
1848
0
    else if (level < 10)
1849
0
    {
1850
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1851
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1852
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1853
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1854
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1855
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1856
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1857
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1858
0
    }
1859
0
}
1860
1861
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1862
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1863
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1864
0
{
1865
0
    IM_ASSERT(tess_tol > 0.0f);
1866
0
    ImVec2 p_last = p1;
1867
0
    ImVec2 p_closest;
1868
0
    float p_closest_dist2 = FLT_MAX;
1869
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1870
0
    return p_closest;
1871
0
}
1872
1873
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1874
0
{
1875
0
    ImVec2 ap = p - a;
1876
0
    ImVec2 ab_dir = b - a;
1877
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1878
0
    if (dot < 0.0f)
1879
0
        return a;
1880
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1881
0
    if (dot > ab_len_sqr)
1882
0
        return b;
1883
0
    return a + ab_dir * dot / ab_len_sqr;
1884
0
}
1885
1886
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1887
0
{
1888
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1889
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1890
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1891
0
    return ((b1 == b2) && (b2 == b3));
1892
0
}
1893
1894
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1895
0
{
1896
0
    ImVec2 v0 = b - a;
1897
0
    ImVec2 v1 = c - a;
1898
0
    ImVec2 v2 = p - a;
1899
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1900
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1901
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1902
0
    out_u = 1.0f - out_v - out_w;
1903
0
}
1904
1905
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1906
0
{
1907
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1908
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1909
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1910
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1911
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1912
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1913
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1914
0
    if (m == dist2_ab)
1915
0
        return proj_ab;
1916
0
    if (m == dist2_bc)
1917
0
        return proj_bc;
1918
0
    return proj_ca;
1919
0
}
1920
1921
//-----------------------------------------------------------------------------
1922
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1923
//-----------------------------------------------------------------------------
1924
1925
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1926
int ImStricmp(const char* str1, const char* str2)
1927
0
{
1928
0
    int d;
1929
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1930
0
    return d;
1931
0
}
1932
1933
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1934
0
{
1935
0
    int d = 0;
1936
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1937
0
    return d;
1938
0
}
1939
1940
void ImStrncpy(char* dst, const char* src, size_t count)
1941
95
{
1942
95
    if (count < 1)
1943
0
        return;
1944
95
    if (count > 1)
1945
95
        strncpy(dst, src, count - 1);
1946
95
    dst[count - 1] = 0;
1947
95
}
1948
1949
char* ImStrdup(const char* str)
1950
3
{
1951
3
    size_t len = strlen(str);
1952
3
    void* buf = IM_ALLOC(len + 1);
1953
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1954
3
}
1955
1956
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1957
0
{
1958
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1959
0
    size_t src_size = strlen(src) + 1;
1960
0
    if (dst_buf_size < src_size)
1961
0
    {
1962
0
        IM_FREE(dst);
1963
0
        dst = (char*)IM_ALLOC(src_size);
1964
0
        if (p_dst_size)
1965
0
            *p_dst_size = src_size;
1966
0
    }
1967
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1968
0
}
1969
1970
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1971
0
{
1972
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1973
0
    return p;
1974
0
}
1975
1976
int ImStrlenW(const ImWchar* str)
1977
0
{
1978
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1979
0
    int n = 0;
1980
0
    while (*str++) n++;
1981
0
    return n;
1982
0
}
1983
1984
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1985
const char* ImStreolRange(const char* str, const char* str_end)
1986
0
{
1987
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1988
0
    return p ? p : str_end;
1989
0
}
1990
1991
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1992
0
{
1993
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1994
0
        buf_mid_line--;
1995
0
    return buf_mid_line;
1996
0
}
1997
1998
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1999
0
{
2000
0
    if (!needle_end)
2001
0
        needle_end = needle + strlen(needle);
2002
2003
0
    const char un0 = (char)ImToUpper(*needle);
2004
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2005
0
    {
2006
0
        if (ImToUpper(*haystack) == un0)
2007
0
        {
2008
0
            const char* b = needle + 1;
2009
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
2010
0
                if (ImToUpper(*a) != ImToUpper(*b))
2011
0
                    break;
2012
0
            if (b == needle_end)
2013
0
                return haystack;
2014
0
        }
2015
0
        haystack++;
2016
0
    }
2017
0
    return NULL;
2018
0
}
2019
2020
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2021
void ImStrTrimBlanks(char* buf)
2022
0
{
2023
0
    char* p = buf;
2024
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
2025
0
        p++;
2026
0
    char* p_start = p;
2027
0
    while (*p != 0)                         // Find end of string
2028
0
        p++;
2029
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
2030
0
        p--;
2031
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
2032
0
        memmove(buf, p_start, p - p_start);
2033
0
    buf[p - p_start] = 0;                   // Zero terminate
2034
0
}
2035
2036
const char* ImStrSkipBlank(const char* str)
2037
0
{
2038
0
    while (str[0] == ' ' || str[0] == '\t')
2039
0
        str++;
2040
0
    return str;
2041
0
}
2042
2043
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2044
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2045
// B) When buf==NULL vsnprintf() will return the output size.
2046
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2047
2048
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2049
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2050
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2051
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2052
#ifdef IMGUI_USE_STB_SPRINTF
2053
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2054
#define STB_SPRINTF_IMPLEMENTATION
2055
#endif
2056
#ifdef IMGUI_STB_SPRINTF_FILENAME
2057
#include IMGUI_STB_SPRINTF_FILENAME
2058
#else
2059
#include "stb_sprintf.h"
2060
#endif
2061
#endif // #ifdef IMGUI_USE_STB_SPRINTF
2062
2063
#if defined(_MSC_VER) && !defined(vsnprintf)
2064
#define vsnprintf _vsnprintf
2065
#endif
2066
2067
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2068
1
{
2069
1
    va_list args;
2070
1
    va_start(args, fmt);
2071
#ifdef IMGUI_USE_STB_SPRINTF
2072
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2073
#else
2074
1
    int w = vsnprintf(buf, buf_size, fmt, args);
2075
1
#endif
2076
1
    va_end(args);
2077
1
    if (buf == NULL)
2078
0
        return w;
2079
1
    if (w == -1 || w >= (int)buf_size)
2080
0
        w = (int)buf_size - 1;
2081
1
    buf[w] = 0;
2082
1
    return w;
2083
1
}
2084
2085
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2086
22.9k
{
2087
#ifdef IMGUI_USE_STB_SPRINTF
2088
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2089
#else
2090
22.9k
    int w = vsnprintf(buf, buf_size, fmt, args);
2091
22.9k
#endif
2092
22.9k
    if (buf == NULL)
2093
0
        return w;
2094
22.9k
    if (w == -1 || w >= (int)buf_size)
2095
0
        w = (int)buf_size - 1;
2096
22.9k
    buf[w] = 0;
2097
22.9k
    return w;
2098
22.9k
}
2099
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2100
2101
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2102
22.9k
{
2103
22.9k
    va_list args;
2104
22.9k
    va_start(args, fmt);
2105
22.9k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2106
22.9k
    va_end(args);
2107
22.9k
}
2108
2109
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2110
22.9k
{
2111
22.9k
    ImGuiContext& g = *GImGui;
2112
22.9k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2113
0
    {
2114
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2115
0
        if (buf == NULL)
2116
0
            buf = "(null)";
2117
0
        *out_buf = buf;
2118
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2119
0
    }
2120
22.9k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2121
0
    {
2122
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2123
0
        const char* buf = va_arg(args, const char*);
2124
0
        if (buf == NULL)
2125
0
        {
2126
0
            buf = "(null)";
2127
0
            buf_len = ImMin(buf_len, 6);
2128
0
        }
2129
0
        *out_buf = buf;
2130
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2131
0
    }
2132
22.9k
    else
2133
22.9k
    {
2134
22.9k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2135
22.9k
        *out_buf = g.TempBuffer.Data;
2136
22.9k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2137
22.9k
    }
2138
22.9k
}
2139
2140
// CRC32 needs a 1KB lookup table (not cache friendly)
2141
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2142
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2143
static const ImU32 GCrc32LookupTable[256] =
2144
{
2145
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2146
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2147
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2148
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2149
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2150
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2151
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2152
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2153
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2154
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2155
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2156
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2157
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2158
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2159
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2160
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2161
};
2162
2163
// Known size hash
2164
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2165
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2166
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2167
137k
{
2168
137k
    ImU32 crc = ~seed;
2169
137k
    const unsigned char* data = (const unsigned char*)data_p;
2170
137k
    const ImU32* crc32_lut = GCrc32LookupTable;
2171
688k
    while (data_size-- != 0)
2172
550k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2173
137k
    return ~crc;
2174
137k
}
2175
2176
// Zero-terminated string hash, with support for ### to reset back to seed value
2177
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2178
// Because this syntax is rarely used we are optimizing for the common case.
2179
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2180
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2181
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2182
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2183
828k
{
2184
828k
    seed = ~seed;
2185
828k
    ImU32 crc = seed;
2186
828k
    const unsigned char* data = (const unsigned char*)data_p;
2187
828k
    const ImU32* crc32_lut = GCrc32LookupTable;
2188
828k
    if (data_size != 0)
2189
0
    {
2190
0
        while (data_size-- != 0)
2191
0
        {
2192
0
            unsigned char c = *data++;
2193
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2194
0
                crc = seed;
2195
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2196
0
        }
2197
0
    }
2198
828k
    else
2199
828k
    {
2200
11.3M
        while (unsigned char c = *data++)
2201
10.5M
        {
2202
10.5M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2203
138k
                crc = seed;
2204
10.5M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2205
10.5M
        }
2206
828k
    }
2207
828k
    return ~crc;
2208
828k
}
2209
2210
//-----------------------------------------------------------------------------
2211
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2212
//-----------------------------------------------------------------------------
2213
2214
// Default file functions
2215
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2216
2217
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2218
0
{
2219
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2220
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2221
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2222
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2223
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2224
2225
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2226
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2227
    wchar_t local_temp_stack[FILENAME_MAX];
2228
    ImVector<wchar_t> local_temp_heap;
2229
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2230
        local_temp_heap.resize(filename_wsize + mode_wsize);
2231
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2232
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2233
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2234
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2235
    return ::_wfopen(filename_wbuf, mode_wbuf);
2236
#else
2237
0
    return fopen(filename, mode);
2238
0
#endif
2239
0
}
2240
2241
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2242
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2243
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2244
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2245
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2246
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2247
2248
// Helper: Load file content into memory
2249
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2250
// This can't really be used with "rt" because fseek size won't match read size.
2251
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2252
0
{
2253
0
    IM_ASSERT(filename && mode);
2254
0
    if (out_file_size)
2255
0
        *out_file_size = 0;
2256
2257
0
    ImFileHandle f;
2258
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2259
0
        return NULL;
2260
2261
0
    size_t file_size = (size_t)ImFileGetSize(f);
2262
0
    if (file_size == (size_t)-1)
2263
0
    {
2264
0
        ImFileClose(f);
2265
0
        return NULL;
2266
0
    }
2267
2268
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2269
0
    if (file_data == NULL)
2270
0
    {
2271
0
        ImFileClose(f);
2272
0
        return NULL;
2273
0
    }
2274
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2275
0
    {
2276
0
        ImFileClose(f);
2277
0
        IM_FREE(file_data);
2278
0
        return NULL;
2279
0
    }
2280
0
    if (padding_bytes > 0)
2281
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2282
2283
0
    ImFileClose(f);
2284
0
    if (out_file_size)
2285
0
        *out_file_size = file_size;
2286
2287
0
    return file_data;
2288
0
}
2289
2290
//-----------------------------------------------------------------------------
2291
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2292
//-----------------------------------------------------------------------------
2293
2294
IM_MSVC_RUNTIME_CHECKS_OFF
2295
2296
// Convert UTF-8 to 32-bit character, process single character input.
2297
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2298
// We handle UTF-8 decoding error by skipping forward.
2299
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2300
547k
{
2301
547k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2302
547k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2303
547k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2304
547k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2305
547k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2306
547k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2307
547k
    int wanted = len + (len ? 0 : 1);
2308
2309
547k
    if (in_text_end == NULL)
2310
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2311
2312
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2313
    // so it is fast even with excessive branching.
2314
547k
    unsigned char s[4];
2315
547k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2316
547k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2317
547k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2318
547k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2319
2320
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2321
547k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2322
547k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2323
547k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2324
547k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2325
547k
    *out_char >>= shiftc[len];
2326
2327
    // Accumulate the various error conditions.
2328
547k
    int e = 0;
2329
547k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2330
547k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2331
547k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2332
547k
    e |= (s[1] & 0xc0) >> 2;
2333
547k
    e |= (s[2] & 0xc0) >> 4;
2334
547k
    e |= (s[3]       ) >> 6;
2335
547k
    e ^= 0x2a; // top two bits of each tail byte correct?
2336
547k
    e >>= shifte[len];
2337
2338
547k
    if (e)
2339
43.9k
    {
2340
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2341
        // One byte is consumed in case of invalid first byte of in_text.
2342
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2343
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2344
43.9k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2345
43.9k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2346
43.9k
    }
2347
2348
547k
    return wanted;
2349
547k
}
2350
2351
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2352
0
{
2353
0
    ImWchar* buf_out = buf;
2354
0
    ImWchar* buf_end = buf + buf_size;
2355
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2356
0
    {
2357
0
        unsigned int c;
2358
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2359
0
        *buf_out++ = (ImWchar)c;
2360
0
    }
2361
0
    *buf_out = 0;
2362
0
    if (in_text_remaining)
2363
0
        *in_text_remaining = in_text;
2364
0
    return (int)(buf_out - buf);
2365
0
}
2366
2367
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2368
0
{
2369
0
    int char_count = 0;
2370
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2371
0
    {
2372
0
        unsigned int c;
2373
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2374
0
        char_count++;
2375
0
    }
2376
0
    return char_count;
2377
0
}
2378
2379
// Based on stb_to_utf8() from github.com/nothings/stb/
2380
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2381
0
{
2382
0
    if (c < 0x80)
2383
0
    {
2384
0
        buf[0] = (char)c;
2385
0
        return 1;
2386
0
    }
2387
0
    if (c < 0x800)
2388
0
    {
2389
0
        if (buf_size < 2) return 0;
2390
0
        buf[0] = (char)(0xc0 + (c >> 6));
2391
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2392
0
        return 2;
2393
0
    }
2394
0
    if (c < 0x10000)
2395
0
    {
2396
0
        if (buf_size < 3) return 0;
2397
0
        buf[0] = (char)(0xe0 + (c >> 12));
2398
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2399
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2400
0
        return 3;
2401
0
    }
2402
0
    if (c <= 0x10FFFF)
2403
0
    {
2404
0
        if (buf_size < 4) return 0;
2405
0
        buf[0] = (char)(0xf0 + (c >> 18));
2406
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2407
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2408
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2409
0
        return 4;
2410
0
    }
2411
    // Invalid code point, the max unicode is 0x10FFFF
2412
0
    return 0;
2413
0
}
2414
2415
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2416
0
{
2417
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2418
0
    out_buf[count] = 0;
2419
0
    return out_buf;
2420
0
}
2421
2422
// Not optimal but we very rarely use this function.
2423
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2424
0
{
2425
0
    unsigned int unused = 0;
2426
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2427
0
}
2428
2429
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2430
0
{
2431
0
    if (c < 0x80) return 1;
2432
0
    if (c < 0x800) return 2;
2433
0
    if (c < 0x10000) return 3;
2434
0
    if (c <= 0x10FFFF) return 4;
2435
0
    return 3;
2436
0
}
2437
2438
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2439
0
{
2440
0
    char* buf_p = out_buf;
2441
0
    const char* buf_end = out_buf + out_buf_size;
2442
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2443
0
    {
2444
0
        unsigned int c = (unsigned int)(*in_text++);
2445
0
        if (c < 0x80)
2446
0
            *buf_p++ = (char)c;
2447
0
        else
2448
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2449
0
    }
2450
0
    *buf_p = 0;
2451
0
    return (int)(buf_p - out_buf);
2452
0
}
2453
2454
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2455
0
{
2456
0
    int bytes_count = 0;
2457
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2458
0
    {
2459
0
        unsigned int c = (unsigned int)(*in_text++);
2460
0
        if (c < 0x80)
2461
0
            bytes_count++;
2462
0
        else
2463
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2464
0
    }
2465
0
    return bytes_count;
2466
0
}
2467
2468
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2469
0
{
2470
0
    while (in_text_curr > in_text_start)
2471
0
    {
2472
0
        in_text_curr--;
2473
0
        if ((*in_text_curr & 0xC0) != 0x80)
2474
0
            return in_text_curr;
2475
0
    }
2476
0
    return in_text_start;
2477
0
}
2478
2479
int ImTextCountLines(const char* in_text, const char* in_text_end)
2480
0
{
2481
0
    if (in_text_end == NULL)
2482
0
        in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2483
0
    int count = 0;
2484
0
    while (in_text < in_text_end)
2485
0
    {
2486
0
        const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2487
0
        in_text = line_end ? line_end + 1 : in_text_end;
2488
0
        count++;
2489
0
    }
2490
0
    return count;
2491
0
}
2492
2493
IM_MSVC_RUNTIME_CHECKS_RESTORE
2494
2495
//-----------------------------------------------------------------------------
2496
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2497
// Note: The Convert functions are early design which are not consistent with other API.
2498
//-----------------------------------------------------------------------------
2499
2500
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2501
0
{
2502
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2503
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2504
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2505
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2506
0
    return IM_COL32(r, g, b, 0xFF);
2507
0
}
2508
2509
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2510
332k
{
2511
332k
    float s = 1.0f / 255.0f;
2512
332k
    return ImVec4(
2513
332k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2514
332k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2515
332k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2516
332k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2517
332k
}
2518
2519
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2520
1.96M
{
2521
1.96M
    ImU32 out;
2522
1.96M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2523
1.96M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2524
1.96M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2525
1.96M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2526
1.96M
    return out;
2527
1.96M
}
2528
2529
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2530
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2531
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2532
0
{
2533
0
    float K = 0.f;
2534
0
    if (g < b)
2535
0
    {
2536
0
        ImSwap(g, b);
2537
0
        K = -1.f;
2538
0
    }
2539
0
    if (r < g)
2540
0
    {
2541
0
        ImSwap(r, g);
2542
0
        K = -2.f / 6.f - K;
2543
0
    }
2544
2545
0
    const float chroma = r - (g < b ? g : b);
2546
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2547
0
    out_s = chroma / (r + 1e-20f);
2548
0
    out_v = r;
2549
0
}
2550
2551
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2552
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2553
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2554
0
{
2555
0
    if (s == 0.0f)
2556
0
    {
2557
        // gray
2558
0
        out_r = out_g = out_b = v;
2559
0
        return;
2560
0
    }
2561
2562
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2563
0
    int   i = (int)h;
2564
0
    float f = h - (float)i;
2565
0
    float p = v * (1.0f - s);
2566
0
    float q = v * (1.0f - s * f);
2567
0
    float t = v * (1.0f - s * (1.0f - f));
2568
2569
0
    switch (i)
2570
0
    {
2571
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2572
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2573
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2574
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2575
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2576
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2577
0
    }
2578
0
}
2579
2580
//-----------------------------------------------------------------------------
2581
// [SECTION] ImGuiStorage
2582
// Helper: Key->value storage
2583
//-----------------------------------------------------------------------------
2584
2585
// std::lower_bound but without the bullshit
2586
ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2587
300k
{
2588
300k
    ImGuiStoragePair* in_p = in_begin;
2589
901k
    for (size_t count = (size_t)(in_end - in_p); count > 0; )
2590
601k
    {
2591
601k
        size_t count2 = count >> 1;
2592
601k
        ImGuiStoragePair* mid = in_p + count2;
2593
601k
        if (mid->key < key)
2594
161k
        {
2595
161k
            in_p = ++mid;
2596
161k
            count -= count2 + 1;
2597
161k
        }
2598
439k
        else
2599
439k
        {
2600
439k
            count = count2;
2601
439k
        }
2602
601k
    }
2603
300k
    return in_p;
2604
300k
}
2605
2606
static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2607
0
{
2608
    // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2609
0
    ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2610
0
    ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2611
0
    return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2612
0
}
2613
2614
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2615
void ImGuiStorage::BuildSortByKey()
2616
0
{
2617
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2618
0
}
2619
2620
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2621
0
{
2622
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2623
0
    if (it == Data.end() || it->key != key)
2624
0
        return default_val;
2625
0
    return it->val_i;
2626
0
}
2627
2628
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2629
0
{
2630
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2631
0
}
2632
2633
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2634
0
{
2635
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2636
0
    if (it == Data.end() || it->key != key)
2637
0
        return default_val;
2638
0
    return it->val_f;
2639
0
}
2640
2641
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2642
300k
{
2643
300k
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2644
300k
    if (it == Data.end() || it->key != key)
2645
3
        return NULL;
2646
300k
    return it->val_p;
2647
300k
}
2648
2649
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2650
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2651
0
{
2652
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2653
0
    if (it == Data.end() || it->key != key)
2654
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2655
0
    return &it->val_i;
2656
0
}
2657
2658
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2659
0
{
2660
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2661
0
}
2662
2663
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2664
0
{
2665
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2666
0
    if (it == Data.end() || it->key != key)
2667
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2668
0
    return &it->val_f;
2669
0
}
2670
2671
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2672
0
{
2673
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2674
0
    if (it == Data.end() || it->key != key)
2675
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2676
0
    return &it->val_p;
2677
0
}
2678
2679
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2680
void ImGuiStorage::SetInt(ImGuiID key, int val)
2681
0
{
2682
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2683
0
    if (it == Data.end() || it->key != key)
2684
0
        Data.insert(it, ImGuiStoragePair(key, val));
2685
0
    else
2686
0
        it->val_i = val;
2687
0
}
2688
2689
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2690
0
{
2691
0
    SetInt(key, val ? 1 : 0);
2692
0
}
2693
2694
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2695
0
{
2696
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2697
0
    if (it == Data.end() || it->key != key)
2698
0
        Data.insert(it, ImGuiStoragePair(key, val));
2699
0
    else
2700
0
        it->val_f = val;
2701
0
}
2702
2703
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2704
3
{
2705
3
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2706
3
    if (it == Data.end() || it->key != key)
2707
3
        Data.insert(it, ImGuiStoragePair(key, val));
2708
0
    else
2709
0
        it->val_p = val;
2710
3
}
2711
2712
void ImGuiStorage::SetAllInt(int v)
2713
0
{
2714
0
    for (int i = 0; i < Data.Size; i++)
2715
0
        Data[i].val_i = v;
2716
0
}
2717
2718
//-----------------------------------------------------------------------------
2719
// [SECTION] ImGuiTextFilter
2720
//-----------------------------------------------------------------------------
2721
2722
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2723
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2724
0
{
2725
0
    InputBuf[0] = 0;
2726
0
    CountGrep = 0;
2727
0
    if (default_filter)
2728
0
    {
2729
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2730
0
        Build();
2731
0
    }
2732
0
}
2733
2734
bool ImGuiTextFilter::Draw(const char* label, float width)
2735
0
{
2736
0
    if (width != 0.0f)
2737
0
        ImGui::SetNextItemWidth(width);
2738
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2739
0
    if (value_changed)
2740
0
        Build();
2741
0
    return value_changed;
2742
0
}
2743
2744
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2745
0
{
2746
0
    out->resize(0);
2747
0
    const char* wb = b;
2748
0
    const char* we = wb;
2749
0
    while (we < e)
2750
0
    {
2751
0
        if (*we == separator)
2752
0
        {
2753
0
            out->push_back(ImGuiTextRange(wb, we));
2754
0
            wb = we + 1;
2755
0
        }
2756
0
        we++;
2757
0
    }
2758
0
    if (wb != we)
2759
0
        out->push_back(ImGuiTextRange(wb, we));
2760
0
}
2761
2762
void ImGuiTextFilter::Build()
2763
0
{
2764
0
    Filters.resize(0);
2765
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2766
0
    input_range.split(',', &Filters);
2767
2768
0
    CountGrep = 0;
2769
0
    for (ImGuiTextRange& f : Filters)
2770
0
    {
2771
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2772
0
            f.b++;
2773
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2774
0
            f.e--;
2775
0
        if (f.empty())
2776
0
            continue;
2777
0
        if (f.b[0] != '-')
2778
0
            CountGrep += 1;
2779
0
    }
2780
0
}
2781
2782
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2783
0
{
2784
0
    if (Filters.empty())
2785
0
        return true;
2786
2787
0
    if (text == NULL)
2788
0
        text = "";
2789
2790
0
    for (const ImGuiTextRange& f : Filters)
2791
0
    {
2792
0
        if (f.empty())
2793
0
            continue;
2794
0
        if (f.b[0] == '-')
2795
0
        {
2796
            // Subtract
2797
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2798
0
                return false;
2799
0
        }
2800
0
        else
2801
0
        {
2802
            // Grep
2803
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2804
0
                return true;
2805
0
        }
2806
0
    }
2807
2808
    // Implicit * grep
2809
0
    if (CountGrep == 0)
2810
0
        return true;
2811
2812
0
    return false;
2813
0
}
2814
2815
//-----------------------------------------------------------------------------
2816
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2817
//-----------------------------------------------------------------------------
2818
2819
// On some platform vsnprintf() takes va_list by reference and modifies it.
2820
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2821
#ifndef va_copy
2822
#if defined(__GNUC__) || defined(__clang__)
2823
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2824
#else
2825
#define va_copy(dest, src) (dest = src)
2826
#endif
2827
#endif
2828
2829
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2830
2831
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2832
0
{
2833
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2834
2835
    // Add zero-terminator the first time
2836
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2837
0
    const int needed_sz = write_off + len;
2838
0
    if (write_off + len >= Buf.Capacity)
2839
0
    {
2840
0
        int new_capacity = Buf.Capacity * 2;
2841
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2842
0
    }
2843
2844
0
    Buf.resize(needed_sz);
2845
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2846
0
    Buf[write_off - 1 + len] = 0;
2847
0
}
2848
2849
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2850
0
{
2851
0
    va_list args;
2852
0
    va_start(args, fmt);
2853
0
    appendfv(fmt, args);
2854
0
    va_end(args);
2855
0
}
2856
2857
// Helper: Text buffer for logging/accumulating text
2858
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2859
0
{
2860
0
    va_list args_copy;
2861
0
    va_copy(args_copy, args);
2862
2863
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2864
0
    if (len <= 0)
2865
0
    {
2866
0
        va_end(args_copy);
2867
0
        return;
2868
0
    }
2869
2870
    // Add zero-terminator the first time
2871
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2872
0
    const int needed_sz = write_off + len;
2873
0
    if (write_off + len >= Buf.Capacity)
2874
0
    {
2875
0
        int new_capacity = Buf.Capacity * 2;
2876
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2877
0
    }
2878
2879
0
    Buf.resize(needed_sz);
2880
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2881
0
    va_end(args_copy);
2882
0
}
2883
2884
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2885
0
{
2886
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2887
0
    if (old_size == new_size)
2888
0
        return;
2889
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2890
0
        LineOffsets.push_back(EndOffset);
2891
0
    const char* base_end = base + new_size;
2892
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2893
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2894
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2895
0
    EndOffset = ImMax(EndOffset, new_size);
2896
0
}
2897
2898
//-----------------------------------------------------------------------------
2899
// [SECTION] ImGuiListClipper
2900
//-----------------------------------------------------------------------------
2901
2902
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2903
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2904
static bool GetSkipItemForListClipping()
2905
0
{
2906
0
    ImGuiContext& g = *GImGui;
2907
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2908
0
}
2909
2910
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2911
0
{
2912
0
    if (ranges.Size - offset <= 1)
2913
0
        return;
2914
2915
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2916
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2917
0
        for (int i = offset; i < sort_end + offset; ++i)
2918
0
            if (ranges[i].Min > ranges[i + 1].Min)
2919
0
                ImSwap(ranges[i], ranges[i + 1]);
2920
2921
    // Now fuse ranges together as much as possible.
2922
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2923
0
    {
2924
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2925
0
        if (ranges[i - 1].Max < ranges[i].Min)
2926
0
            continue;
2927
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2928
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2929
0
        ranges.erase(ranges.Data + i);
2930
0
        i--;
2931
0
    }
2932
0
}
2933
2934
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2935
0
{
2936
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2937
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2938
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2939
0
    ImGuiContext& g = *GImGui;
2940
0
    ImGuiWindow* window = g.CurrentWindow;
2941
0
    float off_y = pos_y - window->DC.CursorPos.y;
2942
0
    window->DC.CursorPos.y = pos_y;
2943
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2944
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2945
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2946
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2947
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2948
0
    if (ImGuiTable* table = g.CurrentTable)
2949
0
    {
2950
0
        if (table->IsInsideRow)
2951
0
            ImGui::TableEndRow(table);
2952
0
        table->RowPosY2 = window->DC.CursorPos.y;
2953
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2954
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2955
0
        table->RowBgColorCounter += row_increase;
2956
0
    }
2957
0
}
2958
2959
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2960
0
{
2961
    // StartPosY starts from ItemsFrozen hence the subtraction
2962
    // Perform the add and multiply with double to allow seeking through larger ranges
2963
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2964
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2965
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2966
0
}
2967
2968
ImGuiListClipper::ImGuiListClipper()
2969
0
{
2970
0
    memset(this, 0, sizeof(*this));
2971
0
}
2972
2973
ImGuiListClipper::~ImGuiListClipper()
2974
0
{
2975
0
    End();
2976
0
}
2977
2978
void ImGuiListClipper::Begin(int items_count, float items_height)
2979
0
{
2980
0
    if (Ctx == NULL)
2981
0
        Ctx = ImGui::GetCurrentContext();
2982
2983
0
    ImGuiContext& g = *Ctx;
2984
0
    ImGuiWindow* window = g.CurrentWindow;
2985
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2986
2987
0
    if (ImGuiTable* table = g.CurrentTable)
2988
0
        if (table->IsInsideRow)
2989
0
            ImGui::TableEndRow(table);
2990
2991
0
    StartPosY = window->DC.CursorPos.y;
2992
0
    ItemsHeight = items_height;
2993
0
    ItemsCount = items_count;
2994
0
    DisplayStart = -1;
2995
0
    DisplayEnd = 0;
2996
2997
    // Acquire temporary buffer
2998
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2999
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3000
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3001
0
    data->Reset(this);
3002
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3003
0
    TempData = data;
3004
0
}
3005
3006
void ImGuiListClipper::End()
3007
0
{
3008
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3009
0
    {
3010
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3011
0
        ImGuiContext& g = *Ctx;
3012
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3013
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3014
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
3015
3016
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3017
0
        IM_ASSERT(data->ListClipper == this);
3018
0
        data->StepNo = data->Ranges.Size;
3019
0
        if (--g.ClipperTempDataStacked > 0)
3020
0
        {
3021
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3022
0
            data->ListClipper->TempData = data;
3023
0
        }
3024
0
        TempData = NULL;
3025
0
    }
3026
0
    ItemsCount = -1;
3027
0
}
3028
3029
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3030
0
{
3031
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3032
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3033
0
    IM_ASSERT(item_begin <= item_end);
3034
0
    if (item_begin < item_end)
3035
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3036
0
}
3037
3038
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3039
0
{
3040
0
    ImGuiContext& g = *clipper->Ctx;
3041
0
    ImGuiWindow* window = g.CurrentWindow;
3042
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3043
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3044
3045
0
    ImGuiTable* table = g.CurrentTable;
3046
0
    if (table && table->IsInsideRow)
3047
0
        ImGui::TableEndRow(table);
3048
3049
    // No items
3050
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3051
0
        return false;
3052
3053
    // While we are in frozen row state, keep displaying items one by one, unclipped
3054
    // FIXME: Could be stored as a table-agnostic state.
3055
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3056
0
    {
3057
0
        clipper->DisplayStart = data->ItemsFrozen;
3058
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3059
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
3060
0
            data->ItemsFrozen++;
3061
0
        return true;
3062
0
    }
3063
3064
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3065
0
    bool calc_clipping = false;
3066
0
    if (data->StepNo == 0)
3067
0
    {
3068
0
        clipper->StartPosY = window->DC.CursorPos.y;
3069
0
        if (clipper->ItemsHeight <= 0.0f)
3070
0
        {
3071
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3072
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3073
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3074
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3075
0
            data->StepNo = 1;
3076
0
            return true;
3077
0
        }
3078
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
3079
0
    }
3080
3081
    // Step 1: Let the clipper infer height from first range
3082
0
    if (clipper->ItemsHeight <= 0.0f)
3083
0
    {
3084
0
        IM_ASSERT(data->StepNo == 1);
3085
0
        if (table)
3086
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3087
3088
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3089
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3090
0
        if (affected_by_floating_point_precision)
3091
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3092
3093
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3094
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3095
0
    }
3096
3097
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3098
0
    const int already_submitted = clipper->DisplayEnd;
3099
0
    if (calc_clipping)
3100
0
    {
3101
0
        if (g.LogEnabled)
3102
0
        {
3103
            // If logging is active, do not perform any clipping
3104
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3105
0
        }
3106
0
        else
3107
0
        {
3108
            // Add range selected to be included for navigation
3109
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3110
0
            if (is_nav_request)
3111
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3112
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3113
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3114
3115
            // Add focused/active item
3116
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3117
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3118
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3119
3120
            // Add visible range
3121
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3122
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3123
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3124
0
        }
3125
3126
        // Convert position ranges to item index ranges
3127
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3128
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3129
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3130
0
        for (ImGuiListClipperRange& range : data->Ranges)
3131
0
            if (range.PosToIndexConvert)
3132
0
            {
3133
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3134
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3135
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3136
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3137
0
                range.PosToIndexConvert = false;
3138
0
            }
3139
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3140
0
    }
3141
3142
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3143
0
    while (data->StepNo < data->Ranges.Size)
3144
0
    {
3145
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3146
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3147
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3148
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3149
0
        data->StepNo++;
3150
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3151
0
            continue;
3152
0
        return true;
3153
0
    }
3154
3155
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3156
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3157
0
    if (clipper->ItemsCount < INT_MAX)
3158
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3159
3160
0
    return false;
3161
0
}
3162
3163
bool ImGuiListClipper::Step()
3164
0
{
3165
0
    ImGuiContext& g = *Ctx;
3166
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3167
0
    bool ret = ImGuiListClipper_StepInternal(this);
3168
0
    if (ret && (DisplayStart == DisplayEnd))
3169
0
        ret = false;
3170
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3171
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3172
0
    if (need_items_height && ItemsHeight > 0.0f)
3173
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3174
0
    if (ret)
3175
0
    {
3176
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3177
0
    }
3178
0
    else
3179
0
    {
3180
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3181
0
        End();
3182
0
    }
3183
0
    return ret;
3184
0
}
3185
3186
//-----------------------------------------------------------------------------
3187
// [SECTION] STYLING
3188
//-----------------------------------------------------------------------------
3189
3190
ImGuiStyle& ImGui::GetStyle()
3191
193k
{
3192
193k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3193
193k
    return GImGui->Style;
3194
193k
}
3195
3196
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3197
1.76M
{
3198
1.76M
    ImGuiStyle& style = GImGui->Style;
3199
1.76M
    ImVec4 c = style.Colors[idx];
3200
1.76M
    c.w *= style.Alpha * alpha_mul;
3201
1.76M
    return ColorConvertFloat4ToU32(c);
3202
1.76M
}
3203
3204
ImU32 ImGui::GetColorU32(const ImVec4& col)
3205
0
{
3206
0
    ImGuiStyle& style = GImGui->Style;
3207
0
    ImVec4 c = col;
3208
0
    c.w *= style.Alpha;
3209
0
    return ColorConvertFloat4ToU32(c);
3210
0
}
3211
3212
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3213
0
{
3214
0
    ImGuiStyle& style = GImGui->Style;
3215
0
    return style.Colors[idx];
3216
0
}
3217
3218
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3219
0
{
3220
0
    ImGuiStyle& style = GImGui->Style;
3221
0
    alpha_mul *= style.Alpha;
3222
0
    if (alpha_mul >= 1.0f)
3223
0
        return col;
3224
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3225
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3226
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3227
0
}
3228
3229
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3230
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3231
0
{
3232
0
    ImGuiContext& g = *GImGui;
3233
0
    ImGuiColorMod backup;
3234
0
    backup.Col = idx;
3235
0
    backup.BackupValue = g.Style.Colors[idx];
3236
0
    g.ColorStack.push_back(backup);
3237
0
    if (g.DebugFlashStyleColorIdx != idx)
3238
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3239
0
}
3240
3241
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3242
138k
{
3243
138k
    ImGuiContext& g = *GImGui;
3244
138k
    ImGuiColorMod backup;
3245
138k
    backup.Col = idx;
3246
138k
    backup.BackupValue = g.Style.Colors[idx];
3247
138k
    g.ColorStack.push_back(backup);
3248
138k
    if (g.DebugFlashStyleColorIdx != idx)
3249
138k
        g.Style.Colors[idx] = col;
3250
138k
}
3251
3252
void ImGui::PopStyleColor(int count)
3253
138k
{
3254
138k
    ImGuiContext& g = *GImGui;
3255
138k
    if (g.ColorStack.Size < count)
3256
0
    {
3257
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3258
0
        count = g.ColorStack.Size;
3259
0
    }
3260
277k
    while (count > 0)
3261
138k
    {
3262
138k
        ImGuiColorMod& backup = g.ColorStack.back();
3263
138k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3264
138k
        g.ColorStack.pop_back();
3265
138k
        count--;
3266
138k
    }
3267
138k
}
3268
3269
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3270
{
3271
    ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3272
};
3273
3274
static const ImGuiDataVarInfo GStyleVarInfo[] =
3275
{
3276
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                     // ImGuiStyleVar_Alpha
3277
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },             // ImGuiStyleVar_DisabledAlpha
3278
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },             // ImGuiStyleVar_WindowPadding
3279
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },            // ImGuiStyleVar_WindowRounding
3280
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },          // ImGuiStyleVar_WindowBorderSize
3281
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },             // ImGuiStyleVar_WindowMinSize
3282
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },          // ImGuiStyleVar_WindowTitleAlign
3283
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },             // ImGuiStyleVar_ChildRounding
3284
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },           // ImGuiStyleVar_ChildBorderSize
3285
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },             // ImGuiStyleVar_PopupRounding
3286
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },           // ImGuiStyleVar_PopupBorderSize
3287
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },              // ImGuiStyleVar_FramePadding
3288
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },             // ImGuiStyleVar_FrameRounding
3289
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },           // ImGuiStyleVar_FrameBorderSize
3290
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },               // ImGuiStyleVar_ItemSpacing
3291
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },          // ImGuiStyleVar_ItemInnerSpacing
3292
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },             // ImGuiStyleVar_IndentSpacing
3293
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },               // ImGuiStyleVar_CellPadding
3294
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },             // ImGuiStyleVar_ScrollbarSize
3295
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },         // ImGuiStyleVar_ScrollbarRounding
3296
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },               // ImGuiStyleVar_GrabMinSize
3297
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },              // ImGuiStyleVar_GrabRounding
3298
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },               // ImGuiStyleVar_TabRounding
3299
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },             // ImGuiStyleVar_TabBorderSize
3300
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },          // ImGuiStyleVar_TabBarBorderSize
3301
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},    // ImGuiStyleVar_TableAngledHeadersAngle
3302
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3303
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },           // ImGuiStyleVar_ButtonTextAlign
3304
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },       // ImGuiStyleVar_SelectableTextAlign
3305
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},    // ImGuiStyleVar_SeparatorTextBorderSize
3306
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },        // ImGuiStyleVar_SeparatorTextAlign
3307
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },      // ImGuiStyleVar_SeparatorTextPadding
3308
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },      // ImGuiStyleVar_DockingSeparatorSize
3309
};
3310
3311
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3312
277k
{
3313
277k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3314
277k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3315
277k
    return &GStyleVarInfo[idx];
3316
277k
}
3317
3318
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3319
0
{
3320
0
    ImGuiContext& g = *GImGui;
3321
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3322
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3323
0
    {
3324
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3325
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3326
0
        *pvar = val;
3327
0
        return;
3328
0
    }
3329
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3330
0
}
3331
3332
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3333
138k
{
3334
138k
    ImGuiContext& g = *GImGui;
3335
138k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3336
138k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3337
138k
    {
3338
138k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3339
138k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3340
138k
        *pvar = val;
3341
138k
        return;
3342
138k
    }
3343
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3344
0
}
3345
3346
void ImGui::PopStyleVar(int count)
3347
138k
{
3348
138k
    ImGuiContext& g = *GImGui;
3349
138k
    if (g.StyleVarStack.Size < count)
3350
0
    {
3351
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3352
0
        count = g.StyleVarStack.Size;
3353
0
    }
3354
277k
    while (count > 0)
3355
138k
    {
3356
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3357
138k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3358
138k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3359
138k
        void* data = info->GetVarPtr(&g.Style);
3360
138k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3361
138k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3362
138k
        g.StyleVarStack.pop_back();
3363
138k
        count--;
3364
138k
    }
3365
138k
}
3366
3367
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3368
0
{
3369
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3370
0
    switch (idx)
3371
0
    {
3372
0
    case ImGuiCol_Text: return "Text";
3373
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3374
0
    case ImGuiCol_WindowBg: return "WindowBg";
3375
0
    case ImGuiCol_ChildBg: return "ChildBg";
3376
0
    case ImGuiCol_PopupBg: return "PopupBg";
3377
0
    case ImGuiCol_Border: return "Border";
3378
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3379
0
    case ImGuiCol_FrameBg: return "FrameBg";
3380
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3381
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3382
0
    case ImGuiCol_TitleBg: return "TitleBg";
3383
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3384
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3385
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3386
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3387
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3388
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3389
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3390
0
    case ImGuiCol_CheckMark: return "CheckMark";
3391
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3392
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3393
0
    case ImGuiCol_Button: return "Button";
3394
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3395
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3396
0
    case ImGuiCol_Header: return "Header";
3397
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3398
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3399
0
    case ImGuiCol_Separator: return "Separator";
3400
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3401
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3402
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3403
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3404
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3405
0
    case ImGuiCol_TabHovered: return "TabHovered";
3406
0
    case ImGuiCol_Tab: return "Tab";
3407
0
    case ImGuiCol_TabSelected: return "TabSelected";
3408
0
    case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3409
0
    case ImGuiCol_TabDimmed: return "TabDimmed";
3410
0
    case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3411
0
    case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3412
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3413
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3414
0
    case ImGuiCol_PlotLines: return "PlotLines";
3415
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3416
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3417
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3418
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3419
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3420
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3421
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3422
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3423
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3424
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3425
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3426
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3427
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3428
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3429
0
    }
3430
0
    IM_ASSERT(0);
3431
0
    return "Unknown";
3432
0
}
3433
3434
3435
//-----------------------------------------------------------------------------
3436
// [SECTION] RENDER HELPERS
3437
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3438
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3439
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3440
//-----------------------------------------------------------------------------
3441
3442
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3443
555k
{
3444
555k
    const char* text_display_end = text;
3445
555k
    if (!text_end)
3446
555k
        text_end = (const char*)-1;
3447
3448
4.99M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3449
4.44M
        text_display_end++;
3450
555k
    return text_display_end;
3451
555k
}
3452
3453
// Internal ImGui functions to render text
3454
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3455
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3456
0
{
3457
0
    ImGuiContext& g = *GImGui;
3458
0
    ImGuiWindow* window = g.CurrentWindow;
3459
3460
    // Hide anything after a '##' string
3461
0
    const char* text_display_end;
3462
0
    if (hide_text_after_hash)
3463
0
    {
3464
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3465
0
    }
3466
0
    else
3467
0
    {
3468
0
        if (!text_end)
3469
0
            text_end = text + strlen(text); // FIXME-OPT
3470
0
        text_display_end = text_end;
3471
0
    }
3472
3473
0
    if (text != text_display_end)
3474
0
    {
3475
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3476
0
        if (g.LogEnabled)
3477
0
            LogRenderedText(&pos, text, text_display_end);
3478
0
    }
3479
0
}
3480
3481
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3482
0
{
3483
0
    ImGuiContext& g = *GImGui;
3484
0
    ImGuiWindow* window = g.CurrentWindow;
3485
3486
0
    if (!text_end)
3487
0
        text_end = text + strlen(text); // FIXME-OPT
3488
3489
0
    if (text != text_end)
3490
0
    {
3491
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3492
0
        if (g.LogEnabled)
3493
0
            LogRenderedText(&pos, text, text_end);
3494
0
    }
3495
0
}
3496
3497
// Default clip_rect uses (pos_min,pos_max)
3498
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3499
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3500
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3501
// better advantage of the render function taking size into account for coarse clipping.
3502
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3503
277k
{
3504
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3505
277k
    ImVec2 pos = pos_min;
3506
277k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3507
3508
277k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3509
277k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3510
277k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3511
277k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3512
277k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3513
3514
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3515
277k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3516
277k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3517
3518
    // Render
3519
277k
    if (need_clipping)
3520
138k
    {
3521
138k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3522
138k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3523
138k
    }
3524
138k
    else
3525
138k
    {
3526
138k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3527
138k
    }
3528
277k
}
3529
3530
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3531
277k
{
3532
    // Hide anything after a '##' string
3533
277k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3534
277k
    const int text_len = (int)(text_display_end - text);
3535
277k
    if (text_len == 0)
3536
0
        return;
3537
3538
277k
    ImGuiContext& g = *GImGui;
3539
277k
    ImGuiWindow* window = g.CurrentWindow;
3540
277k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3541
277k
    if (g.LogEnabled)
3542
0
        LogRenderedText(&pos_min, text, text_display_end);
3543
277k
}
3544
3545
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3546
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3547
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3548
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3549
0
{
3550
0
    ImGuiContext& g = *GImGui;
3551
0
    if (text_end_full == NULL)
3552
0
        text_end_full = FindRenderedTextEnd(text);
3553
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3554
3555
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3556
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3557
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3558
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3559
0
    if (text_size.x > pos_max.x - pos_min.x)
3560
0
    {
3561
        // Hello wo...
3562
        // |       |   |
3563
        // min   max   ellipsis_max
3564
        //          <-> this is generally some padding value
3565
3566
0
        const ImFont* font = draw_list->_Data->Font;
3567
0
        const float font_size = draw_list->_Data->FontSize;
3568
0
        const float font_scale = font_size / font->FontSize;
3569
0
        const char* text_end_ellipsis = NULL;
3570
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3571
3572
        // We can now claim the space between pos_max.x and ellipsis_max.x
3573
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3574
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3575
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3576
0
        {
3577
            // Always display at least 1 character if there's no room for character + ellipsis
3578
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3579
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3580
0
        }
3581
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3582
0
        {
3583
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3584
0
            text_end_ellipsis--;
3585
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3586
0
        }
3587
3588
        // Render text, render ellipsis
3589
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3590
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3591
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3592
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3593
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3594
0
    }
3595
0
    else
3596
0
    {
3597
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3598
0
    }
3599
3600
0
    if (g.LogEnabled)
3601
0
        LogRenderedText(&pos_min, text, text_end_full);
3602
0
}
3603
3604
// Render a rectangle shaped with optional rounding and borders
3605
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3606
115k
{
3607
115k
    ImGuiContext& g = *GImGui;
3608
115k
    ImGuiWindow* window = g.CurrentWindow;
3609
115k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3610
115k
    const float border_size = g.Style.FrameBorderSize;
3611
115k
    if (border && border_size > 0.0f)
3612
115k
    {
3613
115k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3614
115k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3615
115k
    }
3616
115k
}
3617
3618
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3619
0
{
3620
0
    ImGuiContext& g = *GImGui;
3621
0
    ImGuiWindow* window = g.CurrentWindow;
3622
0
    const float border_size = g.Style.FrameBorderSize;
3623
0
    if (border_size > 0.0f)
3624
0
    {
3625
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3626
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3627
0
    }
3628
0
}
3629
3630
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3631
26.5k
{
3632
26.5k
    ImGuiContext& g = *GImGui;
3633
26.5k
    if (id != g.NavId)
3634
18.2k
        return;
3635
8.37k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3636
359
        return;
3637
8.01k
    ImGuiWindow* window = g.CurrentWindow;
3638
8.01k
    if (window->DC.NavHideHighlightOneFrame)
3639
0
        return;
3640
3641
8.01k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3642
8.01k
    ImRect display_rect = bb;
3643
8.01k
    display_rect.ClipWith(window->ClipRect);
3644
8.01k
    const float thickness = 2.0f;
3645
8.01k
    if (flags & ImGuiNavHighlightFlags_Compact)
3646
7.88k
    {
3647
7.88k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3648
7.88k
    }
3649
132
    else
3650
132
    {
3651
132
        const float distance = 3.0f + thickness * 0.5f;
3652
132
        display_rect.Expand(ImVec2(distance, distance));
3653
132
        bool fully_visible = window->ClipRect.Contains(display_rect);
3654
132
        if (!fully_visible)
3655
122
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3656
132
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3657
132
        if (!fully_visible)
3658
122
            window->DrawList->PopClipRect();
3659
132
    }
3660
8.01k
}
3661
3662
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3663
0
{
3664
0
    ImGuiContext& g = *GImGui;
3665
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3666
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3667
0
    for (ImGuiViewportP* viewport : g.Viewports)
3668
0
    {
3669
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3670
0
        ImVec2 offset, size, uv[4];
3671
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3672
0
            continue;
3673
0
        const ImVec2 pos = base_pos - offset;
3674
0
        const float scale = base_scale * viewport->DpiScale;
3675
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3676
0
            continue;
3677
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3678
0
        ImTextureID tex_id = font_atlas->TexID;
3679
0
        draw_list->PushTextureID(tex_id);
3680
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3681
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3682
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3683
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3684
0
        draw_list->PopTextureID();
3685
0
    }
3686
0
}
3687
3688
//-----------------------------------------------------------------------------
3689
// [SECTION] INITIALIZATION, SHUTDOWN
3690
//-----------------------------------------------------------------------------
3691
3692
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3693
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3694
ImGuiContext* ImGui::GetCurrentContext()
3695
1
{
3696
1
    return GImGui;
3697
1
}
3698
3699
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3700
1
{
3701
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3702
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3703
#else
3704
1
    GImGui = ctx;
3705
1
#endif
3706
1
}
3707
3708
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3709
0
{
3710
0
    GImAllocatorAllocFunc = alloc_func;
3711
0
    GImAllocatorFreeFunc = free_func;
3712
0
    GImAllocatorUserData = user_data;
3713
0
}
3714
3715
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3716
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3717
0
{
3718
0
    *p_alloc_func = GImAllocatorAllocFunc;
3719
0
    *p_free_func = GImAllocatorFreeFunc;
3720
0
    *p_user_data = GImAllocatorUserData;
3721
0
}
3722
3723
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3724
1
{
3725
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3726
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3727
1
    SetCurrentContext(ctx);
3728
1
    Initialize();
3729
1
    if (prev_ctx != NULL)
3730
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3731
1
    return ctx;
3732
1
}
3733
3734
void ImGui::DestroyContext(ImGuiContext* ctx)
3735
0
{
3736
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3737
0
    if (ctx == NULL) //-V1051
3738
0
        ctx = prev_ctx;
3739
0
    SetCurrentContext(ctx);
3740
0
    Shutdown();
3741
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3742
0
    IM_DELETE(ctx);
3743
0
}
3744
3745
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3746
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3747
{
3748
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3749
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3750
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3751
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3752
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3753
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3754
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3755
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3756
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3757
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3758
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3759
};
3760
3761
void ImGui::Initialize()
3762
1
{
3763
1
    ImGuiContext& g = *GImGui;
3764
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3765
3766
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3767
1
    {
3768
1
        ImGuiSettingsHandler ini_handler;
3769
1
        ini_handler.TypeName = "Window";
3770
1
        ini_handler.TypeHash = ImHashStr("Window");
3771
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3772
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3773
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3774
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3775
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3776
1
        AddSettingsHandler(&ini_handler);
3777
1
    }
3778
1
    TableSettingsAddSettingsHandler();
3779
3780
    // Setup default localization table
3781
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3782
3783
    // Setup default platform clipboard/IME handlers.
3784
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3785
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3786
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3787
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3788
3789
    // Create default viewport
3790
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3791
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3792
1
    viewport->Idx = 0;
3793
1
    viewport->PlatformWindowCreated = true;
3794
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3795
1
    g.Viewports.push_back(viewport);
3796
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3797
1
    g.ViewportCreatedCount++;
3798
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3799
3800
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3801
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3802
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3803
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3804
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3805
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3806
64
            g.KeysMayBeCharInput.SetBit(key);
3807
3808
1
#ifdef IMGUI_HAS_DOCK
3809
    // Initialize Docking
3810
1
    DockContextInitialize(&g);
3811
1
#endif
3812
3813
1
    g.Initialized = true;
3814
1
}
3815
3816
// This function is merely here to free heap allocations.
3817
void ImGui::Shutdown()
3818
0
{
3819
0
    ImGuiContext& g = *GImGui;
3820
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3821
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3822
3823
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3824
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3825
0
    {
3826
0
        g.IO.Fonts->Locked = false;
3827
0
        IM_DELETE(g.IO.Fonts);
3828
0
    }
3829
0
    g.IO.Fonts = NULL;
3830
0
    g.DrawListSharedData.TempBuffer.clear();
3831
3832
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3833
0
    if (!g.Initialized)
3834
0
        return;
3835
3836
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3837
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3838
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3839
3840
    // Destroy platform windows
3841
0
    DestroyPlatformWindows();
3842
3843
    // Shutdown extensions
3844
0
    DockContextShutdown(&g);
3845
3846
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3847
3848
    // Clear everything else
3849
0
    g.Windows.clear_delete();
3850
0
    g.WindowsFocusOrder.clear();
3851
0
    g.WindowsTempSortBuffer.clear();
3852
0
    g.CurrentWindow = NULL;
3853
0
    g.CurrentWindowStack.clear();
3854
0
    g.WindowsById.Clear();
3855
0
    g.NavWindow = NULL;
3856
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3857
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3858
0
    g.MovingWindow = NULL;
3859
3860
0
    g.KeysRoutingTable.Clear();
3861
3862
0
    g.ColorStack.clear();
3863
0
    g.StyleVarStack.clear();
3864
0
    g.FontStack.clear();
3865
0
    g.OpenPopupStack.clear();
3866
0
    g.BeginPopupStack.clear();
3867
0
    g.NavTreeNodeStack.clear();
3868
3869
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3870
0
    g.Viewports.clear_delete();
3871
3872
0
    g.TabBars.Clear();
3873
0
    g.CurrentTabBarStack.clear();
3874
0
    g.ShrinkWidthBuffer.clear();
3875
3876
0
    g.ClipperTempData.clear_destruct();
3877
3878
0
    g.Tables.Clear();
3879
0
    g.TablesTempData.clear_destruct();
3880
0
    g.DrawChannelsTempMergeBuffer.clear();
3881
3882
0
    g.ClipboardHandlerData.clear();
3883
0
    g.MenusIdSubmittedThisFrame.clear();
3884
0
    g.InputTextState.ClearFreeMemory();
3885
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3886
3887
0
    g.SettingsWindows.clear();
3888
0
    g.SettingsHandlers.clear();
3889
3890
0
    if (g.LogFile)
3891
0
    {
3892
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3893
0
        if (g.LogFile != stdout)
3894
0
#endif
3895
0
            ImFileClose(g.LogFile);
3896
0
        g.LogFile = NULL;
3897
0
    }
3898
0
    g.LogBuffer.clear();
3899
0
    g.DebugLogBuf.clear();
3900
0
    g.DebugLogIndex.clear();
3901
3902
0
    g.Initialized = false;
3903
0
}
3904
3905
// No specific ordering/dependency support, will see as needed
3906
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3907
0
{
3908
0
    ImGuiContext& g = *ctx;
3909
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3910
0
    g.Hooks.push_back(*hook);
3911
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3912
0
    return g.HookIdNext;
3913
0
}
3914
3915
// Deferred removal, avoiding issue with changing vector while iterating it
3916
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3917
0
{
3918
0
    ImGuiContext& g = *ctx;
3919
0
    IM_ASSERT(hook_id != 0);
3920
0
    for (ImGuiContextHook& hook : g.Hooks)
3921
0
        if (hook.HookId == hook_id)
3922
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3923
0
}
3924
3925
// Call context hooks (used by e.g. test engine)
3926
// We assume a small number of hooks so all stored in same array
3927
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3928
832k
{
3929
832k
    ImGuiContext& g = *ctx;
3930
832k
    for (ImGuiContextHook& hook : g.Hooks)
3931
0
        if (hook.Type == hook_type)
3932
0
            hook.Callback(&g, &hook);
3933
832k
}
3934
3935
3936
//-----------------------------------------------------------------------------
3937
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3938
//-----------------------------------------------------------------------------
3939
3940
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3941
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3942
3
{
3943
3
    memset(this, 0, sizeof(*this));
3944
3
    Ctx = ctx;
3945
3
    Name = ImStrdup(name);
3946
3
    NameBufLen = (int)strlen(name) + 1;
3947
3
    ID = ImHashStr(name);
3948
3
    IDStack.push_back(ID);
3949
3
    ViewportAllowPlatformMonitorExtend = -1;
3950
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3951
3
    MoveId = GetID("#MOVE");
3952
3
    TabId = GetID("#TAB");
3953
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3954
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3955
3
    AutoFitFramesX = AutoFitFramesY = -1;
3956
3
    AutoPosLastDirection = ImGuiDir_None;
3957
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3958
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3959
3
    LastFrameActive = -1;
3960
3
    LastFrameJustFocused = -1;
3961
3
    LastTimeActive = -1.0f;
3962
3
    FontWindowScale = FontDpiScale = 1.0f;
3963
3
    SettingsOffset = -1;
3964
3
    DockOrder = -1;
3965
3
    DrawList = &DrawListInst;
3966
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3967
3
    DrawList->_OwnerName = Name;
3968
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3969
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3970
3
}
3971
3972
ImGuiWindow::~ImGuiWindow()
3973
0
{
3974
0
    IM_ASSERT(DrawList == &DrawListInst);
3975
0
    IM_DELETE(Name);
3976
0
    ColumnsStorage.clear_destruct();
3977
0
}
3978
3979
static void SetCurrentWindow(ImGuiWindow* window)
3980
601k
{
3981
601k
    ImGuiContext& g = *GImGui;
3982
601k
    g.CurrentWindow = window;
3983
601k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3984
601k
    if (window)
3985
462k
    {
3986
462k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3987
462k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3988
462k
    }
3989
601k
}
3990
3991
void ImGui::GcCompactTransientMiscBuffers()
3992
0
{
3993
0
    ImGuiContext& g = *GImGui;
3994
0
    g.ItemFlagsStack.clear();
3995
0
    g.GroupStack.clear();
3996
0
    TableGcCompactSettings();
3997
0
}
3998
3999
// Free up/compact internal window buffers, we can use this when a window becomes unused.
4000
// Not freed:
4001
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4002
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4003
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4004
3
{
4005
3
    window->MemoryCompacted = true;
4006
3
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4007
3
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4008
3
    window->IDStack.clear();
4009
3
    window->DrawList->_ClearFreeMemory();
4010
3
    window->DC.ChildWindows.clear();
4011
3
    window->DC.ItemWidthStack.clear();
4012
3
    window->DC.TextWrapPosStack.clear();
4013
3
}
4014
4015
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4016
2
{
4017
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4018
    // The other buffers tends to amortize much faster.
4019
2
    window->MemoryCompacted = false;
4020
2
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4021
2
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4022
2
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4023
2
}
4024
4025
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4026
248
{
4027
248
    ImGuiContext& g = *GImGui;
4028
4029
    // Clear previous active id
4030
248
    if (g.ActiveId != 0)
4031
31
    {
4032
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
4033
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4034
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4035
31
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4036
0
        {
4037
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4038
0
            g.MovingWindow = NULL;
4039
0
        }
4040
4041
        // This could be written in a more general way (e.g associate a hook to ActiveId),
4042
        // but since this is currently quite an exception we'll leave it as is.
4043
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4044
31
        if (g.InputTextState.ID == g.ActiveId)
4045
0
            InputTextDeactivateHook(g.ActiveId);
4046
31
    }
4047
4048
    // Set active id
4049
248
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
4050
248
    if (g.ActiveIdIsJustActivated)
4051
62
    {
4052
62
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4053
62
        g.ActiveIdTimer = 0.0f;
4054
62
        g.ActiveIdHasBeenPressedBefore = false;
4055
62
        g.ActiveIdHasBeenEditedBefore = false;
4056
62
        g.ActiveIdMouseButton = -1;
4057
62
        if (id != 0)
4058
31
        {
4059
31
            g.LastActiveId = id;
4060
31
            g.LastActiveIdTimer = 0.0f;
4061
31
        }
4062
62
    }
4063
248
    g.ActiveId = id;
4064
248
    g.ActiveIdAllowOverlap = false;
4065
248
    g.ActiveIdNoClearOnFocusLoss = false;
4066
248
    g.ActiveIdWindow = window;
4067
248
    g.ActiveIdHasBeenEditedThisFrame = false;
4068
248
    g.ActiveIdFromShortcut = false;
4069
248
    if (id)
4070
31
    {
4071
31
        g.ActiveIdIsAlive = id;
4072
31
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4073
31
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4074
31
    }
4075
4076
    // Clear declaration of inputs claimed by the widget
4077
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4078
248
    g.ActiveIdUsingNavDirMask = 0x00;
4079
248
    g.ActiveIdUsingAllKeyboardKeys = false;
4080
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4081
    g.ActiveIdUsingNavInputMask = 0x00;
4082
#endif
4083
248
}
4084
4085
void ImGui::ClearActiveID()
4086
217
{
4087
217
    SetActiveID(0, NULL); // g.ActiveId = 0;
4088
217
}
4089
4090
void ImGui::SetHoveredID(ImGuiID id)
4091
58
{
4092
58
    ImGuiContext& g = *GImGui;
4093
58
    g.HoveredId = id;
4094
58
    g.HoveredIdAllowOverlap = false;
4095
58
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4096
9
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4097
58
}
4098
4099
ImGuiID ImGui::GetHoveredID()
4100
0
{
4101
0
    ImGuiContext& g = *GImGui;
4102
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4103
0
}
4104
4105
void ImGui::MarkItemEdited(ImGuiID id)
4106
0
{
4107
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4108
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4109
0
    ImGuiContext& g = *GImGui;
4110
0
    if (g.LockMarkEdited > 0)
4111
0
        return;
4112
0
    if (g.ActiveId == id || g.ActiveId == 0)
4113
0
    {
4114
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4115
0
        g.ActiveIdHasBeenEditedBefore = true;
4116
0
    }
4117
4118
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4119
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4120
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4121
4122
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4123
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4124
0
}
4125
4126
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4127
84
{
4128
    // An active popup disable hovering on other windows (apart from its own children)
4129
    // FIXME-OPT: This could be cached/stored within the window.
4130
84
    ImGuiContext& g = *GImGui;
4131
84
    if (g.NavWindow)
4132
8
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4133
8
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4134
0
            {
4135
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4136
                // NB: The 'else' is important because Modal windows are also Popups.
4137
0
                bool want_inhibit = false;
4138
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4139
0
                    want_inhibit = true;
4140
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4141
0
                    want_inhibit = true;
4142
4143
                // Inhibit hover unless the window is within the stack of our modal/popup
4144
0
                if (want_inhibit)
4145
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4146
0
                        return false;
4147
0
            }
4148
4149
    // Filter by viewport
4150
84
    if (window->Viewport != g.MouseViewport)
4151
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4152
0
            return false;
4153
4154
84
    return true;
4155
84
}
4156
4157
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4158
0
{
4159
0
    ImGuiContext& g = *GImGui;
4160
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4161
0
        return g.Style.HoverDelayNormal;
4162
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4163
0
        return g.Style.HoverDelayShort;
4164
0
    return 0.0f;
4165
0
}
4166
4167
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4168
0
{
4169
    // Allow instance flags to override shared flags
4170
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4171
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4172
0
    return user_flags | shared_flags;
4173
0
}
4174
4175
// This is roughly matching the behavior of internal-facing ItemHoverable()
4176
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4177
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4178
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4179
0
{
4180
0
    ImGuiContext& g = *GImGui;
4181
0
    ImGuiWindow* window = g.CurrentWindow;
4182
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4183
4184
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4185
0
    {
4186
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4187
0
            return false;
4188
0
        if (!IsItemFocused())
4189
0
            return false;
4190
4191
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4192
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4193
0
    }
4194
0
    else
4195
0
    {
4196
        // Test for bounding box overlap, as updated as ItemAdd()
4197
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4198
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4199
0
            return false;
4200
4201
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4202
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4203
4204
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4205
4206
        // Done with rectangle culling so we can perform heavier checks now
4207
        // Test if we are hovering the right window (our window could be behind another window)
4208
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4209
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4210
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4211
        // the test that has been running for a long while.
4212
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4213
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4214
0
                return false;
4215
4216
        // Test if another item is active (e.g. being dragged)
4217
0
        const ImGuiID id = g.LastItemData.ID;
4218
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4219
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4220
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4221
0
                    return false;
4222
4223
        // Test if interactions on this window are blocked by an active popup or modal.
4224
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4225
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4226
0
            return false;
4227
4228
        // Test if the item is disabled
4229
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4230
0
            return false;
4231
4232
        // Special handling for calling after Begin() which represent the title bar or tab.
4233
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4234
        // will never be overwritten so we need to detect the case.
4235
0
        if (id == window->MoveId && window->WriteAccessed)
4236
0
            return false;
4237
4238
        // Test if using AllowOverlap and overlapped
4239
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4240
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4241
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4242
0
                    return false;
4243
0
    }
4244
4245
    // Handle hover delay
4246
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4247
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4248
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4249
0
    {
4250
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4251
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4252
0
            g.HoverItemDelayTimer = 0.0f;
4253
0
        g.HoverItemDelayId = hover_delay_id;
4254
4255
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4256
        // but once unlocked on a given item we also moving.
4257
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4258
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4259
0
            return false;
4260
4261
0
        if (g.HoverItemDelayTimer < delay)
4262
0
            return false;
4263
0
    }
4264
4265
0
    return true;
4266
0
}
4267
4268
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4269
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4270
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4271
// If you used this in your legacy/custom widgets code:
4272
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4273
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4274
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4275
427k
{
4276
427k
    ImGuiContext& g = *GImGui;
4277
427k
    ImGuiWindow* window = g.CurrentWindow;
4278
427k
    if (g.HoveredWindow != window)
4279
423k
        return false;
4280
4.70k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4281
4.65k
        return false;
4282
4283
58
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4284
0
        return false;
4285
58
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4286
0
        if (!g.ActiveIdFromShortcut)
4287
0
            return false;
4288
4289
    // Done with rectangle culling so we can perform heavier checks now.
4290
58
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4291
0
    {
4292
0
        g.HoveredIdIsDisabled = true;
4293
0
        return false;
4294
0
    }
4295
4296
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4297
    // hover test in widgets code. We could also decide to split this function is two.
4298
58
    if (id != 0)
4299
58
    {
4300
        // Drag source doesn't report as hovered
4301
58
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4302
0
            return false;
4303
4304
58
        SetHoveredID(id);
4305
4306
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4307
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4308
58
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4309
0
        {
4310
0
            g.HoveredIdAllowOverlap = true;
4311
0
            if (g.HoveredIdPreviousFrame != id)
4312
0
                return false;
4313
0
        }
4314
4315
        // Display shortcut (only works with mouse)
4316
        // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4317
58
        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4318
0
            if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4319
0
                SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4320
58
    }
4321
4322
    // When disabled we'll return false but still set HoveredId
4323
58
    if (item_flags & ImGuiItemFlags_Disabled)
4324
0
    {
4325
        // Release active id if turning disabled
4326
0
        if (g.ActiveId == id && id != 0)
4327
0
            ClearActiveID();
4328
0
        g.HoveredIdIsDisabled = true;
4329
0
        return false;
4330
0
    }
4331
4332
58
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4333
58
    if (id != 0)
4334
58
    {
4335
        // [DEBUG] Item Picker tool!
4336
        // We perform the check here because reaching is path is rare (1~ time a frame),
4337
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4338
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4339
58
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4340
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4341
58
        if (g.DebugItemPickerBreakId == id)
4342
0
            IM_DEBUG_BREAK();
4343
58
    }
4344
58
#endif
4345
4346
58
    if (g.NavDisableMouseHover)
4347
0
        return false;
4348
4349
58
    return true;
4350
58
}
4351
4352
// FIXME: This is inlined/duplicated in ItemAdd()
4353
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4354
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4355
0
{
4356
0
    ImGuiContext& g = *GImGui;
4357
0
    ImGuiWindow* window = g.CurrentWindow;
4358
0
    if (!bb.Overlaps(window->ClipRect))
4359
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4360
0
            if (!g.ItemUnclipByLog)
4361
0
                return true;
4362
0
    return false;
4363
0
}
4364
4365
// This is also inlined in ItemAdd()
4366
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4367
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4368
300k
{
4369
300k
    ImGuiContext& g = *GImGui;
4370
300k
    g.LastItemData.ID = item_id;
4371
300k
    g.LastItemData.InFlags = in_flags;
4372
300k
    g.LastItemData.StatusFlags = item_flags;
4373
300k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4374
300k
}
4375
4376
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4377
0
{
4378
0
    if (wrap_pos_x < 0.0f)
4379
0
        return 0.0f;
4380
4381
0
    ImGuiContext& g = *GImGui;
4382
0
    ImGuiWindow* window = g.CurrentWindow;
4383
0
    if (wrap_pos_x == 0.0f)
4384
0
    {
4385
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4386
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4387
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4388
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4389
        //else
4390
0
        wrap_pos_x = window->WorkRect.Max.x;
4391
0
    }
4392
0
    else if (wrap_pos_x > 0.0f)
4393
0
    {
4394
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4395
0
    }
4396
4397
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4398
0
}
4399
4400
// IM_ALLOC() == ImGui::MemAlloc()
4401
void* ImGui::MemAlloc(size_t size)
4402
1.22k
{
4403
1.22k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4404
1.22k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4405
1.22k
    if (ImGuiContext* ctx = GImGui)
4406
1.22k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4407
1.22k
#endif
4408
1.22k
    return ptr;
4409
1.22k
}
4410
4411
// IM_FREE() == ImGui::MemFree()
4412
void ImGui::MemFree(void* ptr)
4413
1.18k
{
4414
1.18k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4415
1.18k
    if (ptr != NULL)
4416
1.17k
        if (ImGuiContext* ctx = GImGui)
4417
1.17k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4418
1.18k
#endif
4419
1.18k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4420
1.18k
}
4421
4422
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4423
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4424
2.39k
{
4425
2.39k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4426
2.39k
    IM_UNUSED(ptr);
4427
2.39k
    if (entry->FrameCount != frame_count)
4428
34
    {
4429
34
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4430
34
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4431
34
        entry->FrameCount = frame_count;
4432
34
        entry->AllocCount = entry->FreeCount = 0;
4433
34
    }
4434
2.39k
    if (size != (size_t)-1)
4435
1.22k
    {
4436
1.22k
        entry->AllocCount++;
4437
1.22k
        info->TotalAllocCount++;
4438
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4439
1.22k
    }
4440
1.17k
    else
4441
1.17k
    {
4442
1.17k
        entry->FreeCount++;
4443
1.17k
        info->TotalFreeCount++;
4444
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4445
1.17k
    }
4446
2.39k
}
4447
4448
const char* ImGui::GetClipboardText()
4449
0
{
4450
0
    ImGuiContext& g = *GImGui;
4451
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4452
0
}
4453
4454
void ImGui::SetClipboardText(const char* text)
4455
0
{
4456
0
    ImGuiContext& g = *GImGui;
4457
0
    if (g.IO.SetClipboardTextFn)
4458
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4459
0
}
4460
4461
const char* ImGui::GetVersion()
4462
0
{
4463
0
    return IMGUI_VERSION;
4464
0
}
4465
4466
ImGuiIO& ImGui::GetIO()
4467
381k
{
4468
381k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4469
381k
    return GImGui->IO;
4470
381k
}
4471
4472
ImGuiPlatformIO& ImGui::GetPlatformIO()
4473
0
{
4474
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4475
0
    return GImGui->PlatformIO;
4476
0
}
4477
4478
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4479
ImDrawData* ImGui::GetDrawData()
4480
138k
{
4481
138k
    ImGuiContext& g = *GImGui;
4482
138k
    ImGuiViewportP* viewport = g.Viewports[0];
4483
138k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4484
138k
}
4485
4486
double ImGui::GetTime()
4487
23
{
4488
23
    return GImGui->Time;
4489
23
}
4490
4491
int ImGui::GetFrameCount()
4492
0
{
4493
0
    return GImGui->FrameCount;
4494
0
}
4495
4496
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4497
0
{
4498
    // Create the draw list on demand, because they are not frequently used for all viewports
4499
0
    ImGuiContext& g = *GImGui;
4500
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4501
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4502
0
    if (draw_list == NULL)
4503
0
    {
4504
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4505
0
        draw_list->_OwnerName = drawlist_name;
4506
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4507
0
    }
4508
4509
    // Our ImDrawList system requires that there is always a command
4510
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4511
0
    {
4512
0
        draw_list->_ResetForNewFrame();
4513
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4514
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4515
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4516
0
    }
4517
0
    return draw_list;
4518
0
}
4519
4520
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4521
0
{
4522
0
    if (viewport == NULL)
4523
0
        viewport = GImGui->CurrentWindow->Viewport;
4524
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4525
0
}
4526
4527
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4528
0
{
4529
0
    if (viewport == NULL)
4530
0
        viewport = GImGui->CurrentWindow->Viewport;
4531
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4532
0
}
4533
4534
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4535
0
{
4536
0
    return &GImGui->DrawListSharedData;
4537
0
}
4538
4539
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4540
27
{
4541
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4542
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4543
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4544
27
    ImGuiContext& g = *GImGui;
4545
27
    FocusWindow(window);
4546
27
    SetActiveID(window->MoveId, window);
4547
27
    g.NavDisableHighlight = true;
4548
27
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4549
27
    g.ActiveIdNoClearOnFocusLoss = true;
4550
27
    SetActiveIdUsingAllKeyboardKeys();
4551
4552
27
    bool can_move_window = true;
4553
27
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4554
1
        can_move_window = false;
4555
27
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4556
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4557
0
            can_move_window = false;
4558
27
    if (can_move_window)
4559
26
        g.MovingWindow = window;
4560
27
}
4561
4562
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4563
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4564
0
{
4565
0
    ImGuiContext& g = *GImGui;
4566
0
    bool can_undock_node = false;
4567
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4568
0
    {
4569
        // Can undock if:
4570
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4571
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4572
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4573
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4574
0
            can_undock_node = true;
4575
0
    }
4576
4577
0
    const bool clicked = IsMouseClicked(0);
4578
0
    const bool dragging = IsMouseDragging(0);
4579
0
    if (can_undock_node && dragging)
4580
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4581
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4582
0
        StartMouseMovingWindow(window);
4583
0
}
4584
4585
// Handle mouse moving window
4586
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4587
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4588
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4589
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4590
void ImGui::UpdateMouseMovingWindowNewFrame()
4591
138k
{
4592
138k
    ImGuiContext& g = *GImGui;
4593
138k
    if (g.MovingWindow != NULL)
4594
170
    {
4595
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4596
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4597
170
        KeepAliveID(g.ActiveId);
4598
170
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4599
170
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4600
4601
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4602
170
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4603
170
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4604
144
        {
4605
144
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4606
144
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4607
4
            {
4608
4
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4609
4
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4610
0
                {
4611
0
                    moving_window->Viewport->Pos = pos;
4612
0
                    moving_window->Viewport->UpdateWorkRect();
4613
0
                }
4614
4
            }
4615
144
            FocusWindow(g.MovingWindow);
4616
144
        }
4617
26
        else
4618
26
        {
4619
26
            if (!window_disappared)
4620
26
            {
4621
                // Try to merge the window back into the main viewport.
4622
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4623
26
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4624
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4625
4626
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4627
26
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4628
26
                    g.MouseViewport = moving_window->Viewport;
4629
4630
                // Clear the NoInput window flag set by the Viewport system
4631
26
                if (moving_window->Viewport)
4632
26
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4633
26
            }
4634
4635
26
            g.MovingWindow = NULL;
4636
26
            ClearActiveID();
4637
26
        }
4638
170
    }
4639
138k
    else
4640
138k
    {
4641
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4642
138k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4643
19
        {
4644
19
            KeepAliveID(g.ActiveId);
4645
19
            if (!g.IO.MouseDown[0])
4646
1
                ClearActiveID();
4647
19
        }
4648
138k
    }
4649
138k
}
4650
4651
// Initiate moving window when clicking on empty space or title bar.
4652
// Handle left-click and right-click focus.
4653
void ImGui::UpdateMouseMovingWindowEndFrame()
4654
138k
{
4655
138k
    ImGuiContext& g = *GImGui;
4656
138k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4657
230
        return;
4658
4659
    // Unless we just made a window/popup appear
4660
138k
    if (g.NavWindow && g.NavWindow->Appearing)
4661
1
        return;
4662
4663
    // Click on empty space to focus window and start moving
4664
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4665
138k
    if (g.IO.MouseClicked[0])
4666
3.88k
    {
4667
        // Handle the edge case of a popup being closed while clicking in its empty space.
4668
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4669
3.88k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4670
3.88k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4671
4672
3.88k
        if (root_window != NULL && !is_closed_popup)
4673
27
        {
4674
27
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4675
4676
            // Cancel moving if clicked outside of title bar
4677
27
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4678
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4679
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4680
0
                        g.MovingWindow = NULL;
4681
4682
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4683
27
            if (g.HoveredIdIsDisabled)
4684
0
                g.MovingWindow = NULL;
4685
27
        }
4686
3.85k
        else if (root_window == NULL && g.NavWindow != NULL)
4687
170
        {
4688
            // Clicking on void disable focus
4689
170
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4690
170
        }
4691
3.88k
    }
4692
4693
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4694
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4695
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4696
138k
    if (g.IO.MouseClicked[1])
4697
464
    {
4698
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4699
        // This is where we can trim the popup stack.
4700
464
        ImGuiWindow* modal = GetTopMostPopupModal();
4701
464
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4702
464
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4703
464
    }
4704
138k
}
4705
4706
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4707
// Need to keep in sync with SetWindowPos()
4708
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4709
0
{
4710
0
    window->Pos += delta;
4711
0
    window->ClipRect.Translate(delta);
4712
0
    window->OuterRectClipped.Translate(delta);
4713
0
    window->InnerRect.Translate(delta);
4714
0
    window->DC.CursorPos += delta;
4715
0
    window->DC.CursorStartPos += delta;
4716
0
    window->DC.CursorMaxPos += delta;
4717
0
    window->DC.IdealMaxPos += delta;
4718
0
}
4719
4720
static void ScaleWindow(ImGuiWindow* window, float scale)
4721
0
{
4722
0
    ImVec2 origin = window->Viewport->Pos;
4723
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4724
0
    window->Size = ImTrunc(window->Size * scale);
4725
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4726
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4727
0
}
4728
4729
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4730
439k
{
4731
439k
    return (window->Active) && (!window->Hidden);
4732
439k
}
4733
4734
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4735
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4736
138k
{
4737
138k
    ImGuiContext& g = *GImGui;
4738
138k
    ImGuiIO& io = g.IO;
4739
4740
    // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4741
    // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4742
138k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4743
4744
    // Find the window hovered by mouse:
4745
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4746
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4747
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4748
138k
    bool clear_hovered_windows = false;
4749
138k
    FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
4750
138k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4751
138k
    g.HoveredWindowBeforeClear = g.HoveredWindow;
4752
4753
    // Modal windows prevents mouse from hovering behind them.
4754
138k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4755
138k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4756
0
        clear_hovered_windows = true;
4757
4758
    // Disabled mouse hovering (we don't currently clear MousePos, we could)
4759
138k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4760
0
        clear_hovered_windows = true;
4761
4762
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4763
    // won't report hovering nor request capture even while dragging over our windows afterward.
4764
138k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4765
138k
    const bool has_open_modal = (modal_window != NULL);
4766
138k
    int mouse_earliest_down = -1;
4767
138k
    bool mouse_any_down = false;
4768
832k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4769
694k
    {
4770
694k
        if (io.MouseClicked[i])
4771
5.92k
        {
4772
5.92k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4773
5.92k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4774
5.92k
        }
4775
694k
        mouse_any_down |= io.MouseDown[i];
4776
694k
        if (io.MouseDown[i])
4777
165k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4778
141k
                mouse_earliest_down = i;
4779
694k
    }
4780
138k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4781
138k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4782
4783
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4784
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4785
138k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4786
138k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4787
100k
        clear_hovered_windows = true;
4788
4789
138k
    if (clear_hovered_windows)
4790
100k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4791
4792
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4793
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4794
138k
    if (g.WantCaptureMouseNextFrame != -1)
4795
0
    {
4796
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4797
0
    }
4798
138k
    else
4799
138k
    {
4800
138k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4801
138k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4802
138k
    }
4803
4804
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4805
138k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4806
138k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4807
7.76k
        io.WantCaptureKeyboard = true;
4808
138k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4809
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4810
4811
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4812
138k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4813
138k
}
4814
4815
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4816
static void SetupDrawListSharedData()
4817
138k
{
4818
138k
    ImGuiContext& g = *GImGui;
4819
138k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4820
138k
    for (ImGuiViewportP* viewport : g.Viewports)
4821
138k
        virtual_space.Add(viewport->GetMainRect());
4822
138k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4823
138k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4824
138k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4825
138k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4826
138k
    if (g.Style.AntiAliasedLines)
4827
138k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4828
138k
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4829
138k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4830
138k
    if (g.Style.AntiAliasedFill)
4831
138k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4832
138k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4833
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4834
138k
}
4835
4836
void ImGui::NewFrame()
4837
138k
{
4838
138k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4839
138k
    ImGuiContext& g = *GImGui;
4840
4841
    // Remove pending delete hooks before frame start.
4842
    // This deferred removal avoid issues of removal while iterating the hook vector
4843
138k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4844
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4845
0
            g.Hooks.erase(&g.Hooks[n]);
4846
4847
138k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4848
4849
    // Check and assert for various common IO and Configuration mistakes
4850
138k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4851
138k
    ErrorCheckNewFrameSanityChecks();
4852
138k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4853
4854
    // Load settings on first frame, save settings when modified (after a delay)
4855
138k
    UpdateSettings();
4856
4857
138k
    g.Time += g.IO.DeltaTime;
4858
138k
    g.WithinFrameScope = true;
4859
138k
    g.FrameCount += 1;
4860
138k
    g.TooltipOverrideCount = 0;
4861
138k
    g.WindowsActiveCount = 0;
4862
138k
    g.MenusIdSubmittedThisFrame.resize(0);
4863
4864
    // Calculate frame-rate for the user, as a purely luxurious feature
4865
138k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4866
138k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4867
138k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4868
138k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4869
138k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4870
4871
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4872
138k
    g.InputEventsTrail.resize(0);
4873
138k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4874
4875
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4876
138k
    UpdateViewportsNewFrame();
4877
4878
    // Setup current font and draw list shared data
4879
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4880
138k
    g.IO.Fonts->Locked = true;
4881
138k
    SetupDrawListSharedData();
4882
138k
    SetCurrentFont(GetDefaultFont());
4883
138k
    IM_ASSERT(g.Font->IsLoaded());
4884
4885
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4886
138k
    for (ImGuiViewportP* viewport : g.Viewports)
4887
138k
    {
4888
138k
        viewport->DrawData = NULL;
4889
138k
        viewport->DrawDataP.Valid = false;
4890
138k
    }
4891
4892
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4893
138k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4894
95
        KeepAliveID(g.DragDropPayload.SourceId);
4895
4896
    // Update HoveredId data
4897
138k
    if (!g.HoveredIdPreviousFrame)
4898
138k
        g.HoveredIdTimer = 0.0f;
4899
138k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4900
138k
        g.HoveredIdNotActiveTimer = 0.0f;
4901
138k
    if (g.HoveredId)
4902
58
        g.HoveredIdTimer += g.IO.DeltaTime;
4903
138k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4904
58
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4905
138k
    g.HoveredIdPreviousFrame = g.HoveredId;
4906
138k
    g.HoveredId = 0;
4907
138k
    g.HoveredIdAllowOverlap = false;
4908
138k
    g.HoveredIdIsDisabled = false;
4909
4910
    // Clear ActiveID if the item is not alive anymore.
4911
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4912
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4913
138k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4914
0
    {
4915
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4916
0
        ClearActiveID();
4917
0
    }
4918
4919
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4920
138k
    if (g.ActiveId)
4921
196
        g.ActiveIdTimer += g.IO.DeltaTime;
4922
138k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4923
138k
    g.ActiveIdPreviousFrame = g.ActiveId;
4924
138k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4925
138k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4926
138k
    g.ActiveIdIsAlive = 0;
4927
138k
    g.ActiveIdHasBeenEditedThisFrame = false;
4928
138k
    g.ActiveIdPreviousFrameIsAlive = false;
4929
138k
    g.ActiveIdIsJustActivated = false;
4930
138k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4931
0
        g.TempInputId = 0;
4932
138k
    if (g.ActiveId == 0)
4933
138k
    {
4934
138k
        g.ActiveIdUsingNavDirMask = 0x00;
4935
138k
        g.ActiveIdUsingAllKeyboardKeys = false;
4936
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4937
        g.ActiveIdUsingNavInputMask = 0x00;
4938
#endif
4939
138k
    }
4940
4941
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4942
    if (g.ActiveId == 0)
4943
        g.ActiveIdUsingNavInputMask = 0;
4944
    else if (g.ActiveIdUsingNavInputMask != 0)
4945
    {
4946
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4947
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4948
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4949
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4950
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4951
            IM_ASSERT(0); // Other values unsupported
4952
    }
4953
#endif
4954
4955
    // Record when we have been stationary as this state is preserved while over same item.
4956
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4957
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4958
138k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4959
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4960
138k
    else if (g.HoverItemDelayId == 0)
4961
138k
        g.HoverItemUnlockedStationaryId = 0;
4962
138k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4963
763
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4964
138k
    else if (g.HoveredWindow == NULL)
4965
137k
        g.HoverWindowUnlockedStationaryId = 0;
4966
4967
    // Update hover delay for IsItemHovered() with delays and tooltips
4968
138k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4969
138k
    if (g.HoverItemDelayId != 0)
4970
0
    {
4971
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4972
0
        g.HoverItemDelayClearTimer = 0.0f;
4973
0
        g.HoverItemDelayId = 0;
4974
0
    }
4975
138k
    else if (g.HoverItemDelayTimer > 0.0f)
4976
0
    {
4977
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4978
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4979
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4980
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4981
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4982
0
    }
4983
4984
    // Drag and drop
4985
138k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4986
138k
    g.DragDropAcceptIdCurr = 0;
4987
138k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4988
138k
    g.DragDropWithinSource = false;
4989
138k
    g.DragDropWithinTarget = false;
4990
138k
    g.DragDropHoldJustPressedId = 0;
4991
4992
    // Close popups on focus lost (currently wip/opt-in)
4993
    //if (g.IO.AppFocusLost)
4994
    //    ClosePopupsExceptModals();
4995
4996
    // Update keyboard input state
4997
138k
    UpdateKeyboardInputs();
4998
4999
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5000
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5001
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5002
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5003
5004
    // Update gamepad/keyboard navigation
5005
138k
    NavUpdate();
5006
5007
    // Update mouse input state
5008
138k
    UpdateMouseInputs();
5009
5010
    // Undocking
5011
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5012
138k
    DockContextNewFrameUpdateUndocking(&g);
5013
5014
    // Find hovered window
5015
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5016
138k
    UpdateHoveredWindowAndCaptureFlags();
5017
5018
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5019
138k
    UpdateMouseMovingWindowNewFrame();
5020
5021
    // Background darkening/whitening
5022
138k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5023
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5024
138k
    else
5025
138k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5026
5027
138k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
5028
138k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5029
5030
    // Platform IME data: reset for the frame
5031
138k
    g.PlatformImeDataPrev = g.PlatformImeData;
5032
138k
    g.PlatformImeData.WantVisible = false;
5033
5034
    // Mouse wheel scrolling, scale
5035
138k
    UpdateMouseWheel();
5036
5037
    // Mark all windows as not visible and compact unused memory.
5038
138k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5039
138k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5040
138k
    for (ImGuiWindow* window : g.Windows)
5041
416k
    {
5042
416k
        window->WasActive = window->Active;
5043
416k
        window->Active = false;
5044
416k
        window->WriteAccessed = false;
5045
416k
        window->BeginCountPreviousFrame = window->BeginCount;
5046
416k
        window->BeginCount = 0;
5047
5048
        // Garbage collect transient buffers of recently unused windows
5049
416k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5050
3
            GcCompactTransientWindowBuffers(window);
5051
416k
    }
5052
5053
    // Garbage collect transient buffers of recently unused tables
5054
138k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5055
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5056
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5057
138k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5058
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5059
0
            TableGcCompactTransientBuffers(&table_temp_data);
5060
138k
    if (g.GcCompactAll)
5061
0
        GcCompactTransientMiscBuffers();
5062
138k
    g.GcCompactAll = false;
5063
5064
    // Closing the focused window restore focus to the first active root window in descending z-order
5065
138k
    if (g.NavWindow && !g.NavWindow->WasActive)
5066
2
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5067
5068
    // No window should be open at the beginning of the frame.
5069
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5070
138k
    g.CurrentWindowStack.resize(0);
5071
138k
    g.BeginPopupStack.resize(0);
5072
138k
    g.ItemFlagsStack.resize(0);
5073
138k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
5074
138k
    g.GroupStack.resize(0);
5075
5076
    // Docking
5077
138k
    DockContextNewFrameUpdateDocking(&g);
5078
5079
    // [DEBUG] Update debug features
5080
138k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5081
138k
    UpdateDebugToolItemPicker();
5082
138k
    UpdateDebugToolStackQueries();
5083
138k
    UpdateDebugToolFlashStyleColor();
5084
138k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5085
0
    {
5086
0
        g.DebugLocateId = 0;
5087
0
        g.DebugBreakInLocateId = false;
5088
0
    }
5089
138k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5090
0
    {
5091
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5092
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5093
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5094
0
    }
5095
138k
#endif
5096
5097
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5098
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5099
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5100
138k
    g.WithinFrameScopeWithImplicitWindow = true;
5101
138k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5102
138k
    Begin("Debug##Default");
5103
138k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5104
5105
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5106
    // allowing to validate correct Begin/End behavior in user code.
5107
138k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5108
138k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5109
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5110
138k
    else
5111
138k
        g.DebugBeginReturnValueCullDepth = -1;
5112
138k
#endif
5113
5114
138k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5115
138k
}
5116
5117
// FIXME: Add a more explicit sort order in the window structure.
5118
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5119
0
{
5120
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5121
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5122
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5123
0
        return d;
5124
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5125
0
        return d;
5126
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5127
0
}
5128
5129
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5130
416k
{
5131
416k
    out_sorted_windows->push_back(window);
5132
416k
    if (window->Active)
5133
161k
    {
5134
161k
        int count = window->DC.ChildWindows.Size;
5135
161k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5136
184k
        for (int i = 0; i < count; i++)
5137
22.9k
        {
5138
22.9k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5139
22.9k
            if (child->Active)
5140
22.9k
                AddWindowToSortBuffer(out_sorted_windows, child);
5141
22.9k
        }
5142
161k
    }
5143
416k
}
5144
5145
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5146
141k
{
5147
141k
    ImGuiContext& g = *GImGui;
5148
141k
    ImGuiViewportP* viewport = window->Viewport;
5149
141k
    IM_ASSERT(viewport != NULL);
5150
141k
    g.IO.MetricsRenderWindows++;
5151
141k
    if (window->DrawList->_Splitter._Count > 1)
5152
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5153
141k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5154
141k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5155
22.9k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5156
3.09k
            AddWindowToDrawData(child, layer);
5157
141k
}
5158
5159
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5160
138k
{
5161
138k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5162
138k
}
5163
5164
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5165
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5166
138k
{
5167
138k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5168
138k
}
5169
5170
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5171
138k
{
5172
138k
    int n = builder->Layers[0]->Size;
5173
138k
    int full_size = n;
5174
277k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5175
138k
        full_size += builder->Layers[i]->Size;
5176
138k
    builder->Layers[0]->resize(full_size);
5177
277k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5178
138k
    {
5179
138k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5180
138k
        if (layer->empty())
5181
138k
            continue;
5182
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5183
0
        n += layer->Size;
5184
0
        layer->resize(0);
5185
0
    }
5186
138k
}
5187
5188
static void InitViewportDrawData(ImGuiViewportP* viewport)
5189
138k
{
5190
138k
    ImGuiIO& io = ImGui::GetIO();
5191
138k
    ImDrawData* draw_data = &viewport->DrawDataP;
5192
5193
138k
    viewport->DrawData = draw_data; // Make publicly accessible
5194
138k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5195
138k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5196
138k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5197
138k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5198
5199
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5200
    // and to allow applications/backends to easily skip rendering.
5201
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5202
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5203
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5204
138k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5205
5206
138k
    draw_data->Valid = true;
5207
138k
    draw_data->CmdListsCount = 0;
5208
138k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5209
138k
    draw_data->DisplayPos = viewport->Pos;
5210
138k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5211
138k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5212
138k
    draw_data->OwnerViewport = viewport;
5213
138k
}
5214
5215
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5216
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5217
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5218
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5219
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5220
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5221
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5222
601k
{
5223
601k
    ImGuiWindow* window = GetCurrentWindow();
5224
601k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5225
601k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5226
601k
}
5227
5228
void ImGui::PopClipRect()
5229
300k
{
5230
300k
    ImGuiWindow* window = GetCurrentWindow();
5231
300k
    window->DrawList->PopClipRect();
5232
300k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5233
300k
}
5234
5235
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5236
0
{
5237
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5238
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5239
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5240
0
    return window;
5241
0
}
5242
5243
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5244
0
{
5245
0
    if ((col & IM_COL32_A_MASK) == 0)
5246
0
        return;
5247
5248
0
    ImGuiViewportP* viewport = window->Viewport;
5249
0
    ImRect viewport_rect = viewport->GetMainRect();
5250
5251
    // Draw behind window by moving the draw command at the FRONT of the draw list
5252
0
    {
5253
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5254
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5255
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5256
0
        draw_list->ChannelsMerge();
5257
0
        if (draw_list->CmdBuffer.Size == 0)
5258
0
            draw_list->AddDrawCmd();
5259
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5260
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5261
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5262
0
        IM_ASSERT(cmd.ElemCount == 6);
5263
0
        draw_list->CmdBuffer.pop_back();
5264
0
        draw_list->CmdBuffer.push_front(cmd);
5265
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5266
0
        draw_list->PopClipRect();
5267
0
    }
5268
5269
    // Draw over sibling docking nodes in a same docking tree
5270
0
    if (window->RootWindow->DockIsActive)
5271
0
    {
5272
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5273
0
        draw_list->ChannelsMerge();
5274
0
        if (draw_list->CmdBuffer.Size == 0)
5275
0
            draw_list->AddDrawCmd();
5276
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5277
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5278
0
        draw_list->PopClipRect();
5279
0
    }
5280
0
}
5281
5282
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5283
0
{
5284
0
    ImGuiContext& g = *GImGui;
5285
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5286
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5287
0
    {
5288
0
        ImGuiWindow* window = g.Windows[i];
5289
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5290
0
            continue;
5291
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5292
0
            break;
5293
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5294
0
            bottom_most_visible_window = window;
5295
0
    }
5296
0
    return bottom_most_visible_window;
5297
0
}
5298
5299
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5300
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5301
static void ImGui::RenderDimmedBackgrounds()
5302
138k
{
5303
138k
    ImGuiContext& g = *GImGui;
5304
138k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5305
138k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5306
138k
        return;
5307
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5308
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5309
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5310
0
        return;
5311
5312
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5313
0
    if (dim_bg_for_modal)
5314
0
    {
5315
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5316
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5317
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5318
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5319
0
    }
5320
0
    else if (dim_bg_for_window_list)
5321
0
    {
5322
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5323
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5324
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5325
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5326
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5327
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5328
5329
        // Draw border around CTRL+Tab target window
5330
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5331
0
        ImGuiViewport* viewport = window->Viewport;
5332
0
        float distance = g.FontSize;
5333
0
        ImRect bb = window->Rect();
5334
0
        bb.Expand(distance);
5335
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5336
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5337
0
        window->DrawList->ChannelsMerge();
5338
0
        if (window->DrawList->CmdBuffer.Size == 0)
5339
0
            window->DrawList->AddDrawCmd();
5340
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5341
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5342
0
        window->DrawList->PopClipRect();
5343
0
    }
5344
5345
    // Draw dimming background on _other_ viewports than the ones our windows are in
5346
0
    for (ImGuiViewportP* viewport : g.Viewports)
5347
0
    {
5348
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5349
0
            continue;
5350
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5351
0
            continue;
5352
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5353
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5354
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5355
0
    }
5356
0
}
5357
5358
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5359
void ImGui::EndFrame()
5360
277k
{
5361
277k
    ImGuiContext& g = *GImGui;
5362
277k
    IM_ASSERT(g.Initialized);
5363
5364
    // Don't process EndFrame() multiple times.
5365
277k
    if (g.FrameCountEnded == g.FrameCount)
5366
138k
        return;
5367
138k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5368
5369
138k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5370
5371
138k
    ErrorCheckEndFrameSanityChecks();
5372
5373
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5374
138k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5375
138k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5376
0
    {
5377
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5378
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5379
0
        if (viewport == NULL)
5380
0
            viewport = GetMainViewport();
5381
0
        g.IO.SetPlatformImeDataFn(viewport, ime_data);
5382
0
    }
5383
5384
    // Hide implicit/fallback "Debug" window if it hasn't been used
5385
138k
    g.WithinFrameScopeWithImplicitWindow = false;
5386
138k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5387
138k
        g.CurrentWindow->Active = false;
5388
138k
    End();
5389
5390
    // Update navigation: CTRL+Tab, wrap-around requests
5391
138k
    NavEndFrame();
5392
5393
    // Update docking
5394
138k
    DockContextEndFrame(&g);
5395
5396
138k
    SetCurrentViewport(NULL, NULL);
5397
5398
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5399
138k
    if (g.DragDropActive)
5400
99
    {
5401
99
        bool is_delivered = g.DragDropPayload.Delivery;
5402
99
        bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5403
99
        if (is_delivered || is_elapsed)
5404
2
            ClearDragDrop();
5405
99
    }
5406
5407
    // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5408
    // If you want to handle source item disappearing: instead of submitting your description tooltip
5409
    // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5410
    // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5411
    // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5412
138k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5413
0
    {
5414
0
        g.DragDropWithinSource = true;
5415
0
        SetTooltip("...");
5416
0
        g.DragDropWithinSource = false;
5417
0
    }
5418
5419
    // End frame
5420
138k
    g.WithinFrameScope = false;
5421
138k
    g.FrameCountEnded = g.FrameCount;
5422
5423
    // Initiate moving window + handle left-click and right-click focus
5424
138k
    UpdateMouseMovingWindowEndFrame();
5425
5426
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5427
138k
    UpdateViewportsEndFrame();
5428
5429
    // Sort the window list so that all child windows are after their parent
5430
    // We cannot do that on FocusWindow() because children may not exist yet
5431
138k
    g.WindowsTempSortBuffer.resize(0);
5432
138k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5433
138k
    for (ImGuiWindow* window : g.Windows)
5434
416k
    {
5435
416k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5436
22.9k
            continue;
5437
393k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5438
393k
    }
5439
5440
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5441
138k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5442
138k
    g.Windows.swap(g.WindowsTempSortBuffer);
5443
138k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5444
5445
    // Unlock font atlas
5446
138k
    g.IO.Fonts->Locked = false;
5447
5448
    // Clear Input data for next frame
5449
138k
    g.IO.MousePosPrev = g.IO.MousePos;
5450
138k
    g.IO.AppFocusLost = false;
5451
138k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5452
138k
    g.IO.InputQueueCharacters.resize(0);
5453
5454
138k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5455
138k
}
5456
5457
// Prepare the data for rendering so you can call GetDrawData()
5458
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5459
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5460
void ImGui::Render()
5461
138k
{
5462
138k
    ImGuiContext& g = *GImGui;
5463
138k
    IM_ASSERT(g.Initialized);
5464
5465
138k
    if (g.FrameCountEnded != g.FrameCount)
5466
138k
        EndFrame();
5467
138k
    if (g.FrameCountRendered == g.FrameCount)
5468
0
        return;
5469
138k
    g.FrameCountRendered = g.FrameCount;
5470
5471
138k
    g.IO.MetricsRenderWindows = 0;
5472
138k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5473
5474
    // Add background ImDrawList (for each active viewport)
5475
138k
    for (ImGuiViewportP* viewport : g.Viewports)
5476
138k
    {
5477
138k
        InitViewportDrawData(viewport);
5478
138k
        if (viewport->BgFgDrawLists[0] != NULL)
5479
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5480
138k
    }
5481
5482
    // Draw modal/window whitening backgrounds
5483
138k
    RenderDimmedBackgrounds();
5484
5485
    // Add ImDrawList to render
5486
138k
    ImGuiWindow* windows_to_render_top_most[2];
5487
138k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5488
138k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5489
138k
    for (ImGuiWindow* window : g.Windows)
5490
416k
    {
5491
416k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5492
416k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5493
138k
            AddRootWindowToDrawData(window);
5494
416k
    }
5495
416k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5496
277k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5497
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5498
5499
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5500
138k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5501
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5502
5503
    // Setup ImDrawData structures for end-user
5504
138k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5505
138k
    for (ImGuiViewportP* viewport : g.Viewports)
5506
138k
    {
5507
138k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5508
5509
        // Add foreground ImDrawList (for each active viewport)
5510
138k
        if (viewport->BgFgDrawLists[1] != NULL)
5511
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5512
5513
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5514
138k
        ImDrawData* draw_data = &viewport->DrawDataP;
5515
138k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5516
138k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5517
141k
            draw_list->_PopUnusedDrawCmd();
5518
5519
138k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5520
138k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5521
138k
    }
5522
5523
138k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5524
138k
}
5525
5526
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5527
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5528
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5529
277k
{
5530
277k
    ImGuiContext& g = *GImGui;
5531
5532
277k
    const char* text_display_end;
5533
277k
    if (hide_text_after_double_hash)
5534
277k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5535
0
    else
5536
0
        text_display_end = text_end;
5537
5538
277k
    ImFont* font = g.Font;
5539
277k
    const float font_size = g.FontSize;
5540
277k
    if (text == text_display_end)
5541
0
        return ImVec2(0.0f, font_size);
5542
277k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5543
5544
    // Round
5545
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5546
    // FIXME: Investigate using ceilf or e.g.
5547
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5548
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5549
277k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5550
5551
277k
    return text_size;
5552
277k
}
5553
5554
// Find window given position, search front-to-back
5555
// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5556
// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5557
//   with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5558
//   called, aka before the next Begin(). Moving window isn't affected.
5559
// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5560
void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5561
138k
{
5562
138k
    ImGuiContext& g = *GImGui;
5563
138k
    ImGuiWindow* hovered_window = NULL;
5564
138k
    ImGuiWindow* hovered_window_under_moving_window = NULL;
5565
5566
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5567
138k
    ImGuiViewportP* backup_moving_window_viewport = NULL;
5568
138k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5569
170
    {
5570
170
        backup_moving_window_viewport = g.MovingWindow->Viewport;
5571
170
        g.MovingWindow->Viewport = g.MouseViewport;
5572
170
        if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5573
170
            hovered_window = g.MovingWindow;
5574
170
    }
5575
5576
138k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5577
138k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5578
550k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5579
414k
    {
5580
414k
        ImGuiWindow* window = g.Windows[i];
5581
414k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5582
414k
        if (!window->Active || window->Hidden)
5583
272k
            continue;
5584
141k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5585
0
            continue;
5586
141k
        IM_ASSERT(window->Viewport);
5587
141k
        if (window->Viewport != g.MouseViewport)
5588
0
            continue;
5589
5590
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5591
141k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5592
141k
        if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5593
139k
            continue;
5594
5595
        // Support for one rectangular hole in any given window
5596
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5597
2.47k
        if (window->HitTestHoleSize.x != 0)
5598
0
        {
5599
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5600
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5601
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5602
0
                continue;
5603
0
        }
5604
5605
2.47k
        if (find_first_and_in_any_viewport)
5606
0
        {
5607
0
            hovered_window = window;
5608
0
            break;
5609
0
        }
5610
2.47k
        else
5611
2.47k
        {
5612
2.47k
            if (hovered_window == NULL)
5613
2.31k
                hovered_window = window;
5614
2.47k
            IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5615
2.47k
            if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5616
2.31k
                hovered_window_under_moving_window = window;
5617
2.47k
            if (hovered_window && hovered_window_under_moving_window)
5618
2.31k
                break;
5619
2.47k
        }
5620
2.47k
    }
5621
5622
138k
    *out_hovered_window = hovered_window;
5623
138k
    if (out_hovered_window_under_moving_window != NULL)
5624
138k
        *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5625
138k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5626
170
        g.MovingWindow->Viewport = backup_moving_window_viewport;
5627
138k
}
5628
5629
bool ImGui::IsItemActive()
5630
277k
{
5631
277k
    ImGuiContext& g = *GImGui;
5632
277k
    if (g.ActiveId)
5633
336
        return g.ActiveId == g.LastItemData.ID;
5634
277k
    return false;
5635
277k
}
5636
5637
bool ImGui::IsItemActivated()
5638
0
{
5639
0
    ImGuiContext& g = *GImGui;
5640
0
    if (g.ActiveId)
5641
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5642
0
            return true;
5643
0
    return false;
5644
0
}
5645
5646
bool ImGui::IsItemDeactivated()
5647
0
{
5648
0
    ImGuiContext& g = *GImGui;
5649
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5650
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5651
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5652
0
}
5653
5654
bool ImGui::IsItemDeactivatedAfterEdit()
5655
0
{
5656
0
    ImGuiContext& g = *GImGui;
5657
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5658
0
}
5659
5660
// == GetItemID() == GetFocusID()
5661
bool ImGui::IsItemFocused()
5662
0
{
5663
0
    ImGuiContext& g = *GImGui;
5664
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5665
0
        return false;
5666
5667
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5668
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5669
0
    ImGuiWindow* window = g.CurrentWindow;
5670
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5671
0
        return false;
5672
5673
0
    return true;
5674
0
}
5675
5676
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5677
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5678
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5679
0
{
5680
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5681
0
}
5682
5683
bool ImGui::IsItemToggledOpen()
5684
0
{
5685
0
    ImGuiContext& g = *GImGui;
5686
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5687
0
}
5688
5689
bool ImGui::IsItemToggledSelection()
5690
0
{
5691
0
    ImGuiContext& g = *GImGui;
5692
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5693
0
}
5694
5695
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5696
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5697
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5698
bool ImGui::IsAnyItemHovered()
5699
0
{
5700
0
    ImGuiContext& g = *GImGui;
5701
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5702
0
}
5703
5704
bool ImGui::IsAnyItemActive()
5705
0
{
5706
0
    ImGuiContext& g = *GImGui;
5707
0
    return g.ActiveId != 0;
5708
0
}
5709
5710
bool ImGui::IsAnyItemFocused()
5711
0
{
5712
0
    ImGuiContext& g = *GImGui;
5713
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5714
0
}
5715
5716
bool ImGui::IsItemVisible()
5717
0
{
5718
0
    ImGuiContext& g = *GImGui;
5719
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5720
0
}
5721
5722
bool ImGui::IsItemEdited()
5723
0
{
5724
0
    ImGuiContext& g = *GImGui;
5725
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5726
0
}
5727
5728
// Allow next item to be overlapped by subsequent items.
5729
// This works by requiring HoveredId to match for two subsequent frames,
5730
// so if a following items overwrite it our interactions will naturally be disabled.
5731
void ImGui::SetNextItemAllowOverlap()
5732
0
{
5733
0
    ImGuiContext& g = *GImGui;
5734
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5735
0
}
5736
5737
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5738
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5739
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5740
void ImGui::SetItemAllowOverlap()
5741
{
5742
    ImGuiContext& g = *GImGui;
5743
    ImGuiID id = g.LastItemData.ID;
5744
    if (g.HoveredId == id)
5745
        g.HoveredIdAllowOverlap = true;
5746
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5747
        g.ActiveIdAllowOverlap = true;
5748
}
5749
#endif
5750
5751
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5752
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5753
163
{
5754
163
    ImGuiContext& g = *GImGui;
5755
163
    IM_ASSERT(g.ActiveId != 0);
5756
163
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5757
163
    g.ActiveIdUsingAllKeyboardKeys = true;
5758
163
    NavMoveRequestCancel();
5759
163
}
5760
5761
ImGuiID ImGui::GetItemID()
5762
0
{
5763
0
    ImGuiContext& g = *GImGui;
5764
0
    return g.LastItemData.ID;
5765
0
}
5766
5767
ImVec2 ImGui::GetItemRectMin()
5768
0
{
5769
0
    ImGuiContext& g = *GImGui;
5770
0
    return g.LastItemData.Rect.Min;
5771
0
}
5772
5773
ImVec2 ImGui::GetItemRectMax()
5774
0
{
5775
0
    ImGuiContext& g = *GImGui;
5776
0
    return g.LastItemData.Rect.Max;
5777
0
}
5778
5779
ImVec2 ImGui::GetItemRectSize()
5780
0
{
5781
0
    ImGuiContext& g = *GImGui;
5782
0
    return g.LastItemData.Rect.GetSize();
5783
0
}
5784
5785
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5786
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5787
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5788
22.9k
{
5789
22.9k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5790
22.9k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5791
22.9k
}
5792
5793
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5794
0
{
5795
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5796
0
}
5797
5798
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5799
22.9k
{
5800
22.9k
    ImGuiContext& g = *GImGui;
5801
22.9k
    ImGuiWindow* parent_window = g.CurrentWindow;
5802
22.9k
    IM_ASSERT(id != 0);
5803
5804
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5805
22.9k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5806
22.9k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5807
22.9k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5808
22.9k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5809
22.9k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5810
0
    {
5811
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5812
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5813
0
    }
5814
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5815
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5816
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5817
    if (window_flags & ImGuiWindowFlags_NavFlattened)
5818
        child_flags |= ImGuiChildFlags_NavFlattened;
5819
#endif
5820
22.9k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5821
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5822
22.9k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5823
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5824
5825
    // Set window flags
5826
22.9k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5827
22.9k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5828
22.9k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5829
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5830
22.9k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5831
22.9k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5832
5833
    // Special framed style
5834
22.9k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5835
0
    {
5836
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5837
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5838
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5839
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5840
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5841
0
        window_flags |= ImGuiWindowFlags_NoMove;
5842
0
    }
5843
5844
    // Forward child flags
5845
22.9k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5846
22.9k
    g.NextWindowData.ChildFlags = child_flags;
5847
5848
    // Forward size
5849
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5850
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5851
22.9k
    const ImVec2 size_avail = GetContentRegionAvail();
5852
22.9k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5853
22.9k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5854
22.9k
    SetNextWindowSize(size);
5855
5856
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5857
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5858
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5859
22.9k
    const char* temp_window_name;
5860
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5861
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5862
    else*/
5863
22.9k
    if (name)
5864
22.9k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5865
0
    else
5866
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5867
5868
    // Set style
5869
22.9k
    const float backup_border_size = g.Style.ChildBorderSize;
5870
22.9k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5871
10.2k
        g.Style.ChildBorderSize = 0.0f;
5872
5873
    // Begin into window
5874
22.9k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5875
5876
    // Restore style
5877
22.9k
    g.Style.ChildBorderSize = backup_border_size;
5878
22.9k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5879
0
    {
5880
0
        PopStyleVar(3);
5881
0
        PopStyleColor();
5882
0
    }
5883
5884
22.9k
    ImGuiWindow* child_window = g.CurrentWindow;
5885
22.9k
    child_window->ChildId = id;
5886
5887
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5888
    // While this is not really documented/defined, it seems that the expected thing to do.
5889
22.9k
    if (child_window->BeginCount == 1)
5890
22.9k
        parent_window->DC.CursorPos = child_window->Pos;
5891
5892
    // Process navigation-in immediately so NavInit can run on first frame
5893
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5894
22.9k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5895
22.9k
    if (g.ActiveId == temp_id_for_activation)
5896
0
        ClearActiveID();
5897
22.9k
    if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5898
0
    {
5899
0
        FocusWindow(child_window);
5900
0
        NavInitWindow(child_window, false);
5901
0
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5902
0
        g.ActiveIdSource = g.NavInputSource;
5903
0
    }
5904
22.9k
    return ret;
5905
22.9k
}
5906
5907
void ImGui::EndChild()
5908
22.9k
{
5909
22.9k
    ImGuiContext& g = *GImGui;
5910
22.9k
    ImGuiWindow* child_window = g.CurrentWindow;
5911
5912
22.9k
    IM_ASSERT(g.WithinEndChild == false);
5913
22.9k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5914
5915
22.9k
    g.WithinEndChild = true;
5916
22.9k
    ImVec2 child_size = child_window->Size;
5917
22.9k
    End();
5918
22.9k
    if (child_window->BeginCount == 1)
5919
22.9k
    {
5920
22.9k
        ImGuiWindow* parent_window = g.CurrentWindow;
5921
22.9k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5922
22.9k
        ItemSize(child_size);
5923
22.9k
        const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5924
22.9k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5925
18.4k
        {
5926
18.4k
            ItemAdd(bb, child_window->ChildId);
5927
18.4k
            RenderNavHighlight(bb, child_window->ChildId);
5928
5929
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5930
18.4k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5931
8.18k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5932
18.4k
        }
5933
4.54k
        else
5934
4.54k
        {
5935
            // Not navigable into
5936
            // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5937
            // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5938
4.54k
            ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
5939
5940
            // But when flattened we directly reach items, adjust active layer mask accordingly
5941
4.54k
            if (nav_flattened)
5942
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5943
4.54k
        }
5944
22.9k
        if (g.HoveredWindow == child_window)
5945
22
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5946
22.9k
    }
5947
22.9k
    g.WithinEndChild = false;
5948
22.9k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5949
22.9k
}
5950
5951
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5952
10
{
5953
10
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5954
10
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5955
10
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5956
10
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5957
10
}
5958
5959
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5960
300k
{
5961
300k
    ImGuiContext& g = *GImGui;
5962
300k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5963
300k
}
5964
5965
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5966
300k
{
5967
300k
    ImGuiID id = ImHashStr(name);
5968
300k
    return FindWindowByID(id);
5969
300k
}
5970
5971
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5972
0
{
5973
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5974
0
    window->ViewportPos = main_viewport->Pos;
5975
0
    if (settings->ViewportId)
5976
0
    {
5977
0
        window->ViewportId = settings->ViewportId;
5978
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5979
0
    }
5980
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5981
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5982
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5983
0
    window->Collapsed = settings->Collapsed;
5984
0
    window->DockId = settings->DockId;
5985
0
    window->DockOrder = settings->DockOrder;
5986
0
}
5987
5988
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5989
300k
{
5990
300k
    ImGuiContext& g = *GImGui;
5991
5992
300k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5993
300k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5994
300k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5995
2
    {
5996
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5997
2
        g.WindowsFocusOrder.push_back(window);
5998
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5999
2
    }
6000
300k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
6001
0
    {
6002
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6003
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6004
0
            g.WindowsFocusOrder[n]->FocusOrder--;
6005
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6006
0
        window->FocusOrder = -1;
6007
0
    }
6008
300k
    window->IsExplicitChild = new_is_explicit_child;
6009
300k
}
6010
6011
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6012
3
{
6013
    // Initial window state with e.g. default/arbitrary window position
6014
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6015
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6016
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
6017
3
    window->Size = window->SizeFull = ImVec2(0, 0);
6018
3
    window->ViewportPos = main_viewport->Pos;
6019
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6020
6021
3
    if (settings != NULL)
6022
0
    {
6023
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6024
0
        ApplyWindowSettings(window, settings);
6025
0
    }
6026
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6027
6028
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6029
0
    {
6030
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
6031
0
        window->AutoFitOnlyGrows = false;
6032
0
    }
6033
3
    else
6034
3
    {
6035
3
        if (window->Size.x <= 0.0f)
6036
3
            window->AutoFitFramesX = 2;
6037
3
        if (window->Size.y <= 0.0f)
6038
3
            window->AutoFitFramesY = 2;
6039
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6040
3
    }
6041
3
}
6042
6043
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6044
3
{
6045
    // Create window the first time
6046
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6047
3
    ImGuiContext& g = *GImGui;
6048
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6049
3
    window->Flags = flags;
6050
3
    g.WindowsById.SetVoidPtr(window->ID, window);
6051
6052
3
    ImGuiWindowSettings* settings = NULL;
6053
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6054
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6055
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6056
6057
3
    InitOrLoadWindowSettings(window, settings);
6058
6059
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6060
0
        g.Windows.push_front(window); // Quite slow but rare and only once
6061
3
    else
6062
3
        g.Windows.push_back(window);
6063
6064
3
    return window;
6065
3
}
6066
6067
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6068
0
{
6069
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6070
0
}
6071
6072
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6073
901k
{
6074
901k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6075
901k
}
6076
6077
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6078
901k
{
6079
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6080
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6081
    // Perhaps should tend further a neater test for this.
6082
901k
    ImGuiContext& g = *GImGui;
6083
901k
    ImVec2 size_min;
6084
901k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6085
68.8k
    {
6086
68.8k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6087
68.8k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6088
68.8k
    }
6089
832k
    else
6090
832k
    {
6091
832k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6092
832k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6093
832k
    }
6094
6095
    // Reduce artifacts with very small windows
6096
901k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6097
901k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6098
901k
    return size_min;
6099
901k
}
6100
6101
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6102
601k
{
6103
601k
    ImGuiContext& g = *GImGui;
6104
601k
    ImVec2 new_size = size_desired;
6105
601k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6106
0
    {
6107
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6108
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6109
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6110
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6111
0
        if (g.NextWindowData.SizeCallback)
6112
0
        {
6113
0
            ImGuiSizeCallbackData data;
6114
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6115
0
            data.Pos = window->Pos;
6116
0
            data.CurrentSize = window->SizeFull;
6117
0
            data.DesiredSize = new_size;
6118
0
            g.NextWindowData.SizeCallback(&data);
6119
0
            new_size = data.DesiredSize;
6120
0
        }
6121
0
        new_size.x = IM_TRUNC(new_size.x);
6122
0
        new_size.y = IM_TRUNC(new_size.y);
6123
0
    }
6124
6125
    // Minimum size
6126
601k
    ImVec2 size_min = CalcWindowMinSize(window);
6127
601k
    return ImMax(new_size, size_min);
6128
601k
}
6129
6130
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6131
300k
{
6132
300k
    bool preserve_old_content_sizes = false;
6133
300k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6134
115k
        preserve_old_content_sizes = true;
6135
184k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6136
19.8k
        preserve_old_content_sizes = true;
6137
300k
    if (preserve_old_content_sizes)
6138
135k
    {
6139
135k
        *content_size_current = window->ContentSize;
6140
135k
        *content_size_ideal = window->ContentSizeIdeal;
6141
135k
        return;
6142
135k
    }
6143
6144
164k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6145
164k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6146
164k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6147
164k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6148
164k
}
6149
6150
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6151
300k
{
6152
300k
    ImGuiContext& g = *GImGui;
6153
300k
    ImGuiStyle& style = g.Style;
6154
300k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6155
300k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6156
300k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6157
300k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6158
300k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6159
0
    {
6160
        // Tooltip always resize
6161
0
        return size_desired;
6162
0
    }
6163
300k
    else
6164
300k
    {
6165
        // Maximum window size is determined by the viewport size or monitor size
6166
300k
        ImVec2 size_min = CalcWindowMinSize(window);
6167
300k
        ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6168
6169
        // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6170
300k
        if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6171
277k
        {
6172
277k
            if (!window->ViewportOwned)
6173
277k
                size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6174
277k
            const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6175
277k
            if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6176
0
                size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6177
277k
        }
6178
6179
300k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6180
6181
        // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6182
        // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6183
        // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6184
300k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6185
0
            size_auto_fit.y = window->SizeFull.y;
6186
300k
        else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6187
0
            size_auto_fit.x = window->SizeFull.x;
6188
6189
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6190
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6191
300k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6192
300k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6193
300k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6194
300k
        if (will_have_scrollbar_x)
6195
22.9k
            size_auto_fit.y += style.ScrollbarSize;
6196
300k
        if (will_have_scrollbar_y)
6197
349
            size_auto_fit.x += style.ScrollbarSize;
6198
300k
        return size_auto_fit;
6199
300k
    }
6200
300k
}
6201
6202
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6203
0
{
6204
0
    ImVec2 size_contents_current;
6205
0
    ImVec2 size_contents_ideal;
6206
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6207
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6208
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6209
0
    return size_final;
6210
0
}
6211
6212
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6213
184k
{
6214
184k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6215
0
        return ImGuiCol_PopupBg;
6216
184k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6217
22.9k
        return ImGuiCol_ChildBg;
6218
161k
    return ImGuiCol_WindowBg;
6219
184k
}
6220
6221
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6222
0
{
6223
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6224
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6225
0
    ImVec2 size_expected = pos_max - pos_min;
6226
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6227
0
    *out_pos = pos_min;
6228
0
    if (corner_norm.x == 0.0f)
6229
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6230
0
    if (corner_norm.y == 0.0f)
6231
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6232
0
    *out_size = size_constrained;
6233
0
}
6234
6235
// Data for resizing from resize grip / corner
6236
struct ImGuiResizeGripDef
6237
{
6238
    ImVec2  CornerPosN;
6239
    ImVec2  InnerDir;
6240
    int     AngleMin12, AngleMax12;
6241
};
6242
static const ImGuiResizeGripDef resize_grip_def[4] =
6243
{
6244
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6245
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6246
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6247
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6248
};
6249
6250
// Data for resizing from borders
6251
struct ImGuiResizeBorderDef
6252
{
6253
    ImVec2  InnerDir;               // Normal toward inside
6254
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6255
    float   OuterAngle;             // Angle toward outside
6256
};
6257
static const ImGuiResizeBorderDef resize_border_def[4] =
6258
{
6259
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6260
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6261
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6262
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6263
};
6264
6265
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6266
91.8k
{
6267
91.8k
    ImRect rect = window->Rect();
6268
91.8k
    if (thickness == 0.0f)
6269
1
        rect.Max -= ImVec2(1, 1);
6270
91.8k
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6271
68.8k
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6272
45.9k
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6273
22.9k
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6274
0
    IM_ASSERT(0);
6275
0
    return ImRect();
6276
22.9k
}
6277
6278
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6279
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6280
0
{
6281
0
    IM_ASSERT(n >= 0 && n < 4);
6282
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6283
0
    id = ImHashStr("#RESIZE", 0, id);
6284
0
    id = ImHashData(&n, sizeof(int), id);
6285
0
    return id;
6286
0
}
6287
6288
// Borders (Left, Right, Up, Down)
6289
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6290
0
{
6291
0
    IM_ASSERT(dir >= 0 && dir < 4);
6292
0
    int n = (int)dir + 4;
6293
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6294
0
    id = ImHashStr("#RESIZE", 0, id);
6295
0
    id = ImHashData(&n, sizeof(int), id);
6296
0
    return id;
6297
0
}
6298
6299
// Handle resize for: Resize Grips, Borders, Gamepad
6300
// Return true when using auto-fit (double-click on resize grip)
6301
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6302
184k
{
6303
184k
    ImGuiContext& g = *GImGui;
6304
184k
    ImGuiWindowFlags flags = window->Flags;
6305
6306
184k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6307
22.9k
        return false;
6308
161k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6309
138k
        return false;
6310
6311
22.9k
    int ret_auto_fit_mask = 0x00;
6312
22.9k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6313
22.9k
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6314
22.9k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6315
6316
22.9k
    ImRect clamp_rect = visibility_rect;
6317
22.9k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6318
22.9k
    if (window_move_from_title_bar)
6319
0
        clamp_rect.Min.y -= window->TitleBarHeight;
6320
6321
22.9k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6322
22.9k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6323
6324
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6325
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6326
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6327
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6328
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6329
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6330
22.9k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6331
22.9k
    if (clip_with_viewport_rect)
6332
22.9k
        window->ClipRect = window->Viewport->GetMainRect();
6333
6334
    // Resize grips and borders are on layer 1
6335
22.9k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6336
6337
    // Manual resize grips
6338
22.9k
    PushID("#RESIZE");
6339
68.8k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6340
45.9k
    {
6341
45.9k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6342
45.9k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6343
6344
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6345
45.9k
        bool hovered, held;
6346
45.9k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6347
45.9k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6348
45.9k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6349
45.9k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6350
45.9k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6351
45.9k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6352
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6353
45.9k
        if (hovered || held)
6354
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6355
6356
45.9k
        if (held && g.IO.MouseDoubleClicked[0])
6357
0
        {
6358
            // Auto-fit when double-clicking
6359
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6360
0
            ret_auto_fit_mask = 0x03; // Both axises
6361
0
            ClearActiveID();
6362
0
        }
6363
45.9k
        else if (held)
6364
0
        {
6365
            // Resize from any of the four corners
6366
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6367
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6368
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6369
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6370
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6371
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6372
0
        }
6373
6374
        // Only lower-left grip is visible before hovering/activating
6375
45.9k
        if (resize_grip_n == 0 || held || hovered)
6376
22.9k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6377
45.9k
    }
6378
6379
22.9k
    int resize_border_mask = 0x00;
6380
22.9k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6381
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6382
22.9k
    else
6383
22.9k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6384
114k
    for (int border_n = 0; border_n < 4; border_n++)
6385
91.8k
    {
6386
91.8k
        if ((resize_border_mask & (1 << border_n)) == 0)
6387
0
            continue;
6388
91.8k
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6389
91.8k
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6390
6391
91.8k
        bool hovered, held;
6392
91.8k
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6393
91.8k
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6394
91.8k
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6395
91.8k
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6396
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6397
91.8k
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6398
6
            hovered = false;
6399
91.8k
        if (hovered || held)
6400
1
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6401
91.8k
        if (held && g.IO.MouseDoubleClicked[0])
6402
0
        {
6403
            // Double-clicking bottom or right border auto-fit on this axis
6404
            // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6405
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6406
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6407
0
            {
6408
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6409
0
                ret_auto_fit_mask |= (1 << axis);
6410
0
                hovered = held = false; // So border doesn't show highlighted at new position
6411
0
            }
6412
0
            ClearActiveID();
6413
0
        }
6414
91.8k
        else if (held)
6415
0
        {
6416
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6417
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6418
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6419
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6420
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6421
0
            {
6422
0
                g.WindowResizeBorderExpectedRect = border_rect;
6423
0
                g.WindowResizeRelativeMode = false;
6424
0
            }
6425
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6426
0
                g.WindowResizeRelativeMode = true;
6427
6428
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6429
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6430
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6431
6432
            // Use absolute mode position
6433
0
            ImVec2 border_target = window->Pos;
6434
0
            border_target[axis] = border_target_abs_mode_for_axis;
6435
6436
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6437
0
            bool ignore_resize = false;
6438
0
            if (g.WindowResizeRelativeMode)
6439
0
            {
6440
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6441
0
                border_target[axis] = border_target_rel_mode_for_axis;
6442
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6443
0
                    ignore_resize = true;
6444
0
            }
6445
6446
            // Clamp, apply
6447
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6448
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6449
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6450
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6451
0
            {
6452
0
                ImGuiWindow* parent_window = window->ParentWindow;
6453
0
                ImGuiWindowFlags parent_flags = parent_window->Flags;
6454
0
                ImRect border_limit_rect = parent_window->InnerRect;
6455
0
                border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6456
0
                if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6457
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6458
0
                if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6459
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6460
0
            }
6461
0
            if (!ignore_resize)
6462
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6463
0
        }
6464
91.8k
        if (hovered)
6465
1
            *border_hovered = border_n;
6466
91.8k
        if (held)
6467
0
            *border_held = border_n;
6468
91.8k
    }
6469
22.9k
    PopID();
6470
6471
    // Restore nav layer
6472
22.9k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6473
6474
    // Navigation resize (keyboard/gamepad)
6475
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6476
    // Not even sure the callback works here.
6477
22.9k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6478
0
    {
6479
0
        ImVec2 nav_resize_dir;
6480
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6481
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6482
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6483
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6484
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6485
0
        {
6486
0
            const float NAV_RESIZE_SPEED = 600.0f;
6487
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6488
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6489
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6490
0
            g.NavWindowingToggleLayer = false;
6491
0
            g.NavDisableMouseHover = true;
6492
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6493
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6494
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6495
0
            {
6496
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6497
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6498
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6499
0
            }
6500
0
        }
6501
0
    }
6502
6503
    // Apply back modified position/size to window
6504
22.9k
    const ImVec2 curr_pos = window->Pos;
6505
22.9k
    const ImVec2 curr_size = window->SizeFull;
6506
22.9k
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6507
0
        window->Size.x = window->SizeFull.x = size_target.x;
6508
22.9k
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6509
0
        window->Size.y = window->SizeFull.y = size_target.y;
6510
22.9k
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6511
0
        window->Pos.x = ImTrunc(pos_target.x);
6512
22.9k
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6513
0
        window->Pos.y = ImTrunc(pos_target.y);
6514
22.9k
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6515
0
        MarkIniSettingsDirty(window);
6516
6517
    // Recalculate next expected border expected coordinates
6518
22.9k
    if (*border_held != -1)
6519
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6520
6521
22.9k
    return ret_auto_fit_mask;
6522
161k
}
6523
6524
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6525
277k
{
6526
277k
    ImGuiContext& g = *GImGui;
6527
277k
    ImVec2 size_for_clamping = window->Size;
6528
277k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
6529
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6530
277k
    else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6531
0
        size_for_clamping.y = window->TitleBarHeight;
6532
277k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6533
277k
}
6534
6535
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6536
1
{
6537
1
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6538
1
    const float rounding = window->WindowRounding;
6539
1
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6540
1
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6541
1
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6542
1
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6543
1
}
6544
6545
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6546
184k
{
6547
184k
    ImGuiContext& g = *GImGui;
6548
184k
    const float border_size = window->WindowBorderSize;
6549
184k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6550
184k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6551
174k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6552
10.2k
    else if (border_size > 0.0f)
6553
0
    {
6554
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6555
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6556
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6557
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6558
0
    }
6559
184k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6560
1
    {
6561
1
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6562
1
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6563
1
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6564
1
    }
6565
184k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6566
0
    {
6567
0
        float y = window->Pos.y + window->TitleBarHeight - 1;
6568
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6569
0
    }
6570
184k
}
6571
6572
// Draw background and borders
6573
// Draw and handle scrollbars
6574
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6575
300k
{
6576
300k
    ImGuiContext& g = *GImGui;
6577
300k
    ImGuiStyle& style = g.Style;
6578
300k
    ImGuiWindowFlags flags = window->Flags;
6579
6580
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6581
300k
    IM_ASSERT(window->BeginCount == 0);
6582
300k
    window->SkipItems = false;
6583
6584
    // Draw window + handle manual resize
6585
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6586
300k
    const float window_rounding = window->WindowRounding;
6587
300k
    const float window_border_size = window->WindowBorderSize;
6588
300k
    if (window->Collapsed)
6589
115k
    {
6590
        // Title bar only
6591
115k
        const float backup_border_size = style.FrameBorderSize;
6592
115k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6593
115k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6594
115k
        if (window->ViewportOwned)
6595
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6596
115k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6597
115k
        g.Style.FrameBorderSize = backup_border_size;
6598
115k
    }
6599
184k
    else
6600
184k
    {
6601
        // Window background
6602
184k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6603
184k
        {
6604
184k
            bool is_docking_transparent_payload = false;
6605
184k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6606
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6607
0
                    is_docking_transparent_payload = true;
6608
6609
184k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6610
184k
            if (window->ViewportOwned)
6611
0
            {
6612
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6613
0
                if (is_docking_transparent_payload)
6614
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6615
0
            }
6616
184k
            else
6617
184k
            {
6618
                // Adjust alpha. For docking
6619
184k
                bool override_alpha = false;
6620
184k
                float alpha = 1.0f;
6621
184k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6622
0
                {
6623
0
                    alpha = g.NextWindowData.BgAlphaVal;
6624
0
                    override_alpha = true;
6625
0
                }
6626
184k
                if (is_docking_transparent_payload)
6627
0
                {
6628
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6629
0
                    override_alpha = true;
6630
0
                }
6631
184k
                if (override_alpha)
6632
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6633
184k
            }
6634
6635
            // Render, for docked windows and host windows we ensure bg goes before decorations
6636
184k
            if (window->DockIsActive)
6637
0
                window->DockNode->LastBgColor = bg_col;
6638
184k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6639
184k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6640
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6641
184k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6642
184k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6643
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6644
184k
        }
6645
184k
        if (window->DockIsActive)
6646
0
            window->DockNode->IsBgDrawnThisFrame = true;
6647
6648
        // Title bar
6649
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6650
        // in order for their pos/size to be matching their undocking state.)
6651
184k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6652
161k
        {
6653
161k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6654
161k
            if (window->ViewportOwned)
6655
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6656
161k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6657
161k
        }
6658
6659
        // Menu bar
6660
184k
        if (flags & ImGuiWindowFlags_MenuBar)
6661
0
        {
6662
0
            ImRect menu_bar_rect = window->MenuBarRect();
6663
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6664
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6665
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6666
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6667
0
        }
6668
6669
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6670
184k
        ImGuiDockNode* node = window->DockNode;
6671
184k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6672
0
        {
6673
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6674
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6675
0
            ImVec2 p = node->Pos;
6676
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6677
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6678
0
            KeepAliveID(unhide_id);
6679
0
            bool hovered, held;
6680
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6681
0
                node->WantHiddenTabBarToggle = true;
6682
0
            else if (held && IsMouseDragging(0))
6683
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6684
6685
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6686
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6687
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6688
0
        }
6689
6690
        // Scrollbars
6691
184k
        if (window->ScrollbarX)
6692
22.9k
            Scrollbar(ImGuiAxis_X);
6693
184k
        if (window->ScrollbarY)
6694
19.3k
            Scrollbar(ImGuiAxis_Y);
6695
6696
        // Render resize grips (after their input handling so we don't have a frame of latency)
6697
184k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6698
161k
        {
6699
485k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6700
323k
            {
6701
323k
                const ImU32 col = resize_grip_col[resize_grip_n];
6702
323k
                if ((col & IM_COL32_A_MASK) == 0)
6703
300k
                    continue;
6704
22.9k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6705
22.9k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6706
22.9k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6707
22.9k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6708
22.9k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6709
22.9k
                window->DrawList->PathFillConvex(col);
6710
22.9k
            }
6711
161k
        }
6712
6713
        // Borders (for dock node host they will be rendered over after the tab bar)
6714
184k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6715
184k
            RenderWindowOuterBorders(window);
6716
184k
    }
6717
300k
}
6718
6719
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6720
// Render title text, collapse button, close button
6721
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6722
277k
{
6723
277k
    ImGuiContext& g = *GImGui;
6724
277k
    ImGuiStyle& style = g.Style;
6725
277k
    ImGuiWindowFlags flags = window->Flags;
6726
6727
277k
    const bool has_close_button = (p_open != NULL);
6728
277k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6729
6730
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6731
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6732
277k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6733
277k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6734
277k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6735
6736
    // Layout buttons
6737
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6738
277k
    float pad_l = style.FramePadding.x;
6739
277k
    float pad_r = style.FramePadding.x;
6740
277k
    float button_sz = g.FontSize;
6741
277k
    ImVec2 close_button_pos;
6742
277k
    ImVec2 collapse_button_pos;
6743
277k
    if (has_close_button)
6744
0
    {
6745
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6746
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6747
0
    }
6748
277k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6749
0
    {
6750
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6751
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6752
0
    }
6753
277k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6754
277k
    {
6755
277k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6756
277k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6757
277k
    }
6758
6759
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6760
277k
    if (has_collapse_button)
6761
277k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6762
4
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6763
6764
    // Close button
6765
277k
    if (has_close_button)
6766
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6767
0
            *p_open = false;
6768
6769
277k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6770
277k
    g.CurrentItemFlags = item_flags_backup;
6771
6772
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6773
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6774
277k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6775
277k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6776
6777
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6778
    // while uncentered title text will still reach edges correctly.
6779
277k
    if (pad_l > style.FramePadding.x)
6780
277k
        pad_l += g.Style.ItemInnerSpacing.x;
6781
277k
    if (pad_r > style.FramePadding.x)
6782
0
        pad_r += g.Style.ItemInnerSpacing.x;
6783
277k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6784
0
    {
6785
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6786
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6787
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6788
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6789
0
    }
6790
6791
277k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6792
277k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6793
277k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6794
0
    {
6795
0
        ImVec2 marker_pos;
6796
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6797
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6798
0
        if (marker_pos.x > layout_r.Min.x)
6799
0
        {
6800
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6801
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6802
0
        }
6803
0
    }
6804
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6805
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6806
277k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6807
277k
}
6808
6809
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6810
300k
{
6811
300k
    window->ParentWindow = parent_window;
6812
300k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6813
300k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6814
22.9k
    {
6815
22.9k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6816
22.9k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6817
22.9k
            window->RootWindow = parent_window->RootWindow;
6818
22.9k
    }
6819
300k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6820
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6821
300k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6822
22.9k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6823
300k
    while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6824
0
    {
6825
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6826
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6827
0
    }
6828
300k
}
6829
6830
// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6831
// This is designed as a toy/test-bed for
6832
void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6833
300k
{
6834
300k
    ImGuiContext& g = *GImGui;
6835
300k
    window->SkipRefresh = false;
6836
300k
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6837
300k
        return;
6838
0
    if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6839
0
    {
6840
        // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6841
0
        if (window->Appearing) // If currently appearing
6842
0
            return;
6843
0
        if (window->Hidden) // If was hidden (previous frame)
6844
0
            return;
6845
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6846
0
            return;
6847
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6848
0
            return;
6849
0
        window->DrawList = NULL;
6850
0
        window->SkipRefresh = true;
6851
0
    }
6852
0
}
6853
6854
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6855
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6856
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6857
// - WindowA            // FindBlockingModal() returns Modal1
6858
//   - WindowB          //                  .. returns Modal1
6859
//   - Modal1           //                  .. returns Modal2
6860
//      - WindowC       //                  .. returns Modal2
6861
//          - WindowD   //                  .. returns Modal2
6862
//          - Modal2    //                  .. returns Modal2
6863
//            - WindowE //                  .. returns NULL
6864
// Notes:
6865
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6866
//   Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6867
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6868
172
{
6869
172
    ImGuiContext& g = *GImGui;
6870
172
    if (g.OpenPopupStack.Size <= 0)
6871
172
        return NULL;
6872
6873
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6874
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6875
0
    {
6876
0
        ImGuiWindow* popup_window = popup_data.Window;
6877
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6878
0
            continue;
6879
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6880
0
            continue;
6881
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6882
0
            return popup_window;
6883
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6884
0
            continue;
6885
0
        return popup_window;                                        // Place window right below first block modal
6886
0
    }
6887
0
    return NULL;
6888
0
}
6889
6890
// Push a new Dear ImGui window to add widgets to.
6891
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6892
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6893
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6894
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6895
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6896
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6897
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6898
300k
{
6899
300k
    ImGuiContext& g = *GImGui;
6900
300k
    const ImGuiStyle& style = g.Style;
6901
300k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6902
300k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6903
300k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6904
6905
    // Find or create
6906
300k
    ImGuiWindow* window = FindWindowByName(name);
6907
300k
    const bool window_just_created = (window == NULL);
6908
300k
    if (window_just_created)
6909
3
        window = CreateNewWindow(name, flags);
6910
6911
    // [DEBUG] Debug break requested by user
6912
300k
    if (g.DebugBreakInWindow == window->ID)
6913
0
        IM_DEBUG_BREAK();
6914
6915
    // Automatically disable manual moving/resizing when NoInputs is set
6916
300k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6917
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6918
6919
300k
    const int current_frame = g.FrameCount;
6920
300k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6921
300k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6922
6923
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6924
300k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6925
300k
    if (flags & ImGuiWindowFlags_Popup)
6926
0
    {
6927
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6928
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6929
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6930
0
    }
6931
6932
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6933
300k
    const bool window_was_appearing = window->Appearing;
6934
300k
    if (first_begin_of_the_frame)
6935
300k
    {
6936
300k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6937
300k
        window->Appearing = window_just_activated_by_user;
6938
300k
        if (window->Appearing)
6939
5
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6940
300k
        window->FlagsPreviousFrame = window->Flags;
6941
300k
        window->Flags = (ImGuiWindowFlags)flags;
6942
300k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6943
300k
        window->LastFrameActive = current_frame;
6944
300k
        window->LastTimeActive = (float)g.Time;
6945
300k
        window->BeginOrderWithinParent = 0;
6946
300k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6947
300k
    }
6948
0
    else
6949
0
    {
6950
0
        flags = window->Flags;
6951
0
    }
6952
6953
    // Docking
6954
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6955
300k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6956
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6957
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6958
300k
    if (first_begin_of_the_frame)
6959
300k
    {
6960
300k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6961
300k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6962
300k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6963
300k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6964
300k
        if (has_dock_node || new_auto_dock_node)
6965
0
        {
6966
0
            BeginDocked(window, p_open);
6967
0
            flags = window->Flags;
6968
0
            if (window->DockIsActive)
6969
0
            {
6970
0
                IM_ASSERT(window->DockNode != NULL);
6971
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6972
0
            }
6973
6974
            // Amend the Appearing flag
6975
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6976
0
            {
6977
0
                window->Appearing = true;
6978
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6979
0
            }
6980
0
        }
6981
300k
        else
6982
300k
        {
6983
300k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6984
300k
        }
6985
300k
    }
6986
6987
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6988
300k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6989
300k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6990
300k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6991
6992
    // We allow window memory to be compacted so recreate the base stack when needed.
6993
300k
    if (window->IDStack.Size == 0)
6994
2
        window->IDStack.push_back(window->ID);
6995
6996
    // Add to stack
6997
300k
    g.CurrentWindow = window;
6998
300k
    ImGuiWindowStackData window_stack_data;
6999
300k
    window_stack_data.Window = window;
7000
300k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7001
300k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
7002
300k
    window_stack_data.DisabledOverrideReenable = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7003
300k
    g.CurrentWindowStack.push_back(window_stack_data);
7004
300k
    if (flags & ImGuiWindowFlags_ChildMenu)
7005
0
        g.BeginMenuDepth++;
7006
7007
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7008
300k
    if (first_begin_of_the_frame)
7009
300k
    {
7010
300k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
7011
300k
        window->ParentWindowInBeginStack = parent_window_in_stack;
7012
7013
        // Focus route
7014
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7015
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7016
300k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7017
300k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7018
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7019
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7020
7021
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7022
300k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
7023
0
        {
7024
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7025
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7026
0
        }
7027
300k
    }
7028
7029
    // Add to focus scope stack
7030
300k
    PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7031
300k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7032
7033
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7034
300k
    if (flags & ImGuiWindowFlags_Popup)
7035
0
    {
7036
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7037
0
        popup_ref.Window = window;
7038
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7039
0
        g.BeginPopupStack.push_back(popup_ref);
7040
0
        window->PopupId = popup_ref.PopupId;
7041
0
    }
7042
7043
    // Process SetNextWindow***() calls
7044
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
7045
300k
    bool window_pos_set_by_api = false;
7046
300k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7047
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7048
0
    {
7049
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7050
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7051
0
        {
7052
            // May be processed on the next frame if this is our first frame and we are measuring size
7053
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7054
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
7055
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7056
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7057
0
        }
7058
0
        else
7059
0
        {
7060
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7061
0
        }
7062
0
    }
7063
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7064
161k
    {
7065
161k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7066
161k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7067
161k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7068
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
7069
161k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7070
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
7071
161k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7072
161k
    }
7073
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7074
0
    {
7075
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
7076
0
        {
7077
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7078
0
            window->ScrollTargetCenterRatio.x = 0.0f;
7079
0
        }
7080
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
7081
0
        {
7082
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7083
0
            window->ScrollTargetCenterRatio.y = 0.0f;
7084
0
        }
7085
0
    }
7086
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7087
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7088
300k
    else if (first_begin_of_the_frame)
7089
300k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7090
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
7091
0
        window->WindowClass = g.NextWindowData.WindowClass;
7092
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7093
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7094
300k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7095
0
        FocusWindow(window);
7096
300k
    if (window->Appearing)
7097
5
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7098
7099
    // [EXPERIMENTAL] Skip Refresh mode
7100
300k
    UpdateWindowSkipRefresh(window);
7101
7102
    // Nested root windows (typically tooltips) override disabled state
7103
300k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7104
0
        BeginDisabledOverrideReenable();
7105
7106
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7107
300k
    g.CurrentWindow = NULL;
7108
7109
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
7110
300k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7111
300k
    {
7112
        // Initialize
7113
300k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7114
300k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7115
300k
        window->Active = true;
7116
300k
        window->HasCloseButton = (p_open != NULL);
7117
300k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7118
300k
        window->IDStack.resize(1);
7119
300k
        window->DrawList->_ResetForNewFrame();
7120
300k
        window->DC.CurrentTableIdx = -1;
7121
300k
        if (flags & ImGuiWindowFlags_DockNodeHost)
7122
0
        {
7123
0
            window->DrawList->ChannelsSplit(2);
7124
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7125
0
        }
7126
7127
        // Restore buffer capacity when woken from a compacted state, to avoid
7128
300k
        if (window->MemoryCompacted)
7129
2
            GcAwakeTransientWindowBuffers(window);
7130
7131
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7132
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7133
300k
        bool window_title_visible_elsewhere = false;
7134
300k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7135
0
            window_title_visible_elsewhere = true;
7136
300k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
7137
0
            window_title_visible_elsewhere = true;
7138
300k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7139
0
        {
7140
0
            size_t buf_len = (size_t)window->NameBufLen;
7141
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7142
0
            window->NameBufLen = (int)buf_len;
7143
0
        }
7144
7145
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7146
7147
        // Update contents size from last frame for auto-fitting (or use explicit size)
7148
300k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7149
7150
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7151
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7152
        // it has a single usage before this code block and may be set below before it is finally checked.
7153
300k
        if (window->HiddenFramesCanSkipItems > 0)
7154
19.8k
            window->HiddenFramesCanSkipItems--;
7155
300k
        if (window->HiddenFramesCannotSkipItems > 0)
7156
2
            window->HiddenFramesCannotSkipItems--;
7157
300k
        if (window->HiddenFramesForRenderOnly > 0)
7158
0
            window->HiddenFramesForRenderOnly--;
7159
7160
        // Hide new windows for one frame until they calculate their size
7161
300k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7162
1
            window->HiddenFramesCannotSkipItems = 1;
7163
7164
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7165
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7166
300k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7167
0
        {
7168
0
            window->HiddenFramesCannotSkipItems = 1;
7169
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7170
0
            {
7171
0
                if (!window_size_x_set_by_api)
7172
0
                    window->Size.x = window->SizeFull.x = 0.f;
7173
0
                if (!window_size_y_set_by_api)
7174
0
                    window->Size.y = window->SizeFull.y = 0.f;
7175
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7176
0
            }
7177
0
        }
7178
7179
        // SELECT VIEWPORT
7180
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7181
7182
300k
        WindowSelectViewport(window);
7183
300k
        SetCurrentViewport(window, window->Viewport);
7184
300k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7185
300k
        SetCurrentWindow(window);
7186
300k
        flags = window->Flags;
7187
7188
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7189
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7190
7191
300k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7192
22.9k
            window->WindowBorderSize = style.ChildBorderSize;
7193
277k
        else
7194
277k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7195
300k
        window->WindowPadding = style.WindowPadding;
7196
300k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7197
10.2k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7198
7199
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7200
300k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7201
300k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7202
300k
        window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7203
300k
        window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7204
7205
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7206
        // Those flags will be altered further down in the function depending on more conditions.
7207
300k
        bool use_current_size_for_scrollbar_x = window_just_created;
7208
300k
        bool use_current_size_for_scrollbar_y = window_just_created;
7209
300k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7210
0
            use_current_size_for_scrollbar_x = true;
7211
300k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7212
0
            use_current_size_for_scrollbar_y = true;
7213
7214
        // Collapse window by double-clicking on title bar
7215
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7216
300k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7217
277k
        {
7218
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7219
277k
            ImRect title_bar_rect = window->TitleBarRect();
7220
277k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7221
778
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7222
3
                    window->WantCollapseToggle = true;
7223
277k
            if (window->WantCollapseToggle)
7224
7
            {
7225
7
                window->Collapsed = !window->Collapsed;
7226
7
                if (!window->Collapsed)
7227
3
                    use_current_size_for_scrollbar_y = true;
7228
7
                MarkIniSettingsDirty(window);
7229
7
            }
7230
277k
        }
7231
22.9k
        else
7232
22.9k
        {
7233
22.9k
            window->Collapsed = false;
7234
22.9k
        }
7235
300k
        window->WantCollapseToggle = false;
7236
7237
        // SIZE
7238
7239
        // Outer Decoration Sizes
7240
        // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7241
300k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7242
300k
        window->DecoOuterSizeX1 = 0.0f;
7243
300k
        window->DecoOuterSizeX2 = 0.0f;
7244
300k
        window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7245
300k
        window->DecoOuterSizeY2 = 0.0f;
7246
300k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7247
7248
        // Calculate auto-fit size, handle automatic resize
7249
300k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7250
300k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7251
0
        {
7252
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7253
0
            if (!window_size_x_set_by_api)
7254
0
            {
7255
0
                window->SizeFull.x = size_auto_fit.x;
7256
0
                use_current_size_for_scrollbar_x = true;
7257
0
            }
7258
0
            if (!window_size_y_set_by_api)
7259
0
            {
7260
0
                window->SizeFull.y = size_auto_fit.y;
7261
0
                use_current_size_for_scrollbar_y = true;
7262
0
            }
7263
0
        }
7264
300k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7265
2
        {
7266
            // Auto-fit may only grow window during the first few frames
7267
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7268
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7269
2
            {
7270
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7271
2
                use_current_size_for_scrollbar_x = true;
7272
2
            }
7273
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7274
2
            {
7275
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7276
2
                use_current_size_for_scrollbar_y = true;
7277
2
            }
7278
2
            if (!window->Collapsed)
7279
2
                MarkIniSettingsDirty(window);
7280
2
        }
7281
7282
        // Apply minimum/maximum window size constraints and final size
7283
300k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7284
300k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7285
7286
        // POSITION
7287
7288
        // Popup latch its initial position, will position itself when it appears next frame
7289
300k
        if (window_just_activated_by_user)
7290
5
        {
7291
5
            window->AutoPosLastDirection = ImGuiDir_None;
7292
5
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7293
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7294
5
        }
7295
7296
        // Position child window
7297
300k
        if (flags & ImGuiWindowFlags_ChildWindow)
7298
22.9k
        {
7299
22.9k
            IM_ASSERT(parent_window && parent_window->Active);
7300
22.9k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7301
22.9k
            parent_window->DC.ChildWindows.push_back(window);
7302
22.9k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7303
22.9k
                window->Pos = parent_window->DC.CursorPos;
7304
22.9k
        }
7305
7306
300k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7307
300k
        if (window_pos_with_pivot)
7308
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7309
300k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7310
0
            window->Pos = FindBestWindowPosForPopup(window);
7311
300k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7312
0
            window->Pos = FindBestWindowPosForPopup(window);
7313
300k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7314
0
            window->Pos = FindBestWindowPosForPopup(window);
7315
7316
        // Late create viewport if we don't fit within our current host viewport.
7317
300k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7318
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7319
0
            {
7320
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7321
                //ImGuiViewport* old_viewport = window->Viewport;
7322
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7323
7324
                // FIXME-DPI
7325
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7326
0
                SetCurrentViewport(window, window->Viewport);
7327
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7328
0
                SetCurrentWindow(window);
7329
0
            }
7330
7331
300k
        if (window->ViewportOwned)
7332
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7333
7334
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7335
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7336
300k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7337
300k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7338
300k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7339
300k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7340
7341
        // Clamp position/size so window stays visible within its viewport or monitor
7342
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7343
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7344
300k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7345
277k
        {
7346
277k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7347
277k
            {
7348
277k
                ClampWindowPos(window, visibility_rect);
7349
277k
            }
7350
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7351
0
            {
7352
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7353
0
                {
7354
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7355
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7356
0
                }
7357
0
                else
7358
0
                {
7359
                    // When not moving ensure visible in its monitor
7360
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7361
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7362
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7363
0
                }
7364
0
                visibility_rect.Expand(-visibility_padding);
7365
0
                ClampWindowPos(window, visibility_rect);
7366
0
            }
7367
277k
        }
7368
300k
        window->Pos = ImTrunc(window->Pos);
7369
7370
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7371
        // Large values tend to lead to variety of artifacts and are not recommended.
7372
300k
        if (window->ViewportOwned || window->DockIsActive)
7373
0
            window->WindowRounding = 0.0f;
7374
300k
        else
7375
300k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7376
7377
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7378
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7379
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7380
7381
        // Apply window focus (new and reactivated windows are moved to front)
7382
300k
        bool want_focus = false;
7383
300k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7384
5
        {
7385
5
            if (flags & ImGuiWindowFlags_Popup)
7386
0
                want_focus = true;
7387
5
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7388
2
                want_focus = true;
7389
5
        }
7390
7391
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7392
#ifdef IMGUI_ENABLE_TEST_ENGINE
7393
        if (g.TestEngineHookItems)
7394
        {
7395
            IM_ASSERT(window->IDStack.Size == 1);
7396
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7397
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7398
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7399
            window->IDStack.Size = 1;
7400
        }
7401
#endif
7402
7403
        // Decide if we are going to handle borders and resize grips
7404
300k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7405
7406
        // Handle manual resize: Resize Grips, Borders, Gamepad
7407
300k
        int border_hovered = -1, border_held = -1;
7408
300k
        ImU32 resize_grip_col[4] = {};
7409
300k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7410
300k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7411
300k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7412
184k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7413
0
            {
7414
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7415
0
                    use_current_size_for_scrollbar_x = true;
7416
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7417
0
                    use_current_size_for_scrollbar_y = true;
7418
0
            }
7419
300k
        window->ResizeBorderHovered = (signed char)border_hovered;
7420
300k
        window->ResizeBorderHeld = (signed char)border_held;
7421
7422
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7423
300k
        if (window->ViewportOwned)
7424
0
        {
7425
0
            if (!window->Viewport->PlatformRequestMove)
7426
0
                window->Viewport->Pos = window->Pos;
7427
0
            if (!window->Viewport->PlatformRequestResize)
7428
0
                window->Viewport->Size = window->Size;
7429
0
            window->Viewport->UpdateWorkRect();
7430
0
            viewport_rect = window->Viewport->GetMainRect();
7431
0
        }
7432
7433
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7434
300k
        window->ViewportPos = window->Viewport->Pos;
7435
7436
        // SCROLLBAR VISIBILITY
7437
7438
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7439
300k
        if (!window->Collapsed)
7440
184k
        {
7441
            // When reading the current size we need to read it after size constraints have been applied.
7442
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7443
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7444
184k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7445
184k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7446
184k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7447
184k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7448
184k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7449
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7450
184k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7451
184k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7452
184k
            if (window->ScrollbarX && !window->ScrollbarY)
7453
5.02k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7454
184k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7455
7456
            // Amend the partially filled window->DecorationXXX values.
7457
184k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7458
184k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7459
184k
        }
7460
7461
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7462
        // Update various regions. Variables they depend on should be set above in this function.
7463
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7464
7465
        // Outer rectangle
7466
        // Not affected by window border size. Used by:
7467
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7468
        // - Begin() initial clipping rect for drawing window background and borders.
7469
        // - Begin() clipping whole child
7470
300k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7471
300k
        const ImRect outer_rect = window->Rect();
7472
300k
        const ImRect title_bar_rect = window->TitleBarRect();
7473
300k
        window->OuterRectClipped = outer_rect;
7474
300k
        if (window->DockIsActive)
7475
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight;
7476
300k
        window->OuterRectClipped.ClipWith(host_rect);
7477
7478
        // Inner rectangle
7479
        // Not affected by window border size. Used by:
7480
        // - InnerClipRect
7481
        // - ScrollToRectEx()
7482
        // - NavUpdatePageUpPageDown()
7483
        // - Scrollbar()
7484
300k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7485
300k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7486
300k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7487
300k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7488
7489
        // Inner clipping rectangle.
7490
        // - Extend a outside of normal work region up to borders.
7491
        // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7492
        // - It also makes clipped items be more noticeable.
7493
        // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7494
        // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7495
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7496
        // Affected by window/frame border size. Used by:
7497
        // - Begin() initial clip rect
7498
300k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7499
300k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7500
300k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7501
300k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7502
300k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7503
300k
        window->InnerClipRect.ClipWithFull(host_rect);
7504
7505
        // Default item width. Make it proportional to window size if window manually resizes
7506
300k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7507
300k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7508
0
        else
7509
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7510
7511
        // SCROLLING
7512
7513
        // Lock down maximum scrolling
7514
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7515
        // for right/bottom aligned items without creating a scrollbar.
7516
300k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7517
300k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7518
7519
        // Apply scrolling
7520
300k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7521
300k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7522
300k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7523
7524
        // DRAWING
7525
7526
        // Setup draw list and outer clipping rectangle
7527
300k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7528
300k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7529
300k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7530
7531
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7532
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7533
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7534
300k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7535
300k
        if (is_undocked_or_docked_visible)
7536
300k
        {
7537
300k
            bool render_decorations_in_parent = false;
7538
300k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7539
22.9k
            {
7540
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7541
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7542
22.9k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7543
22.9k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7544
22.9k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7545
22.9k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7546
22.9k
                    render_decorations_in_parent = true;
7547
22.9k
            }
7548
300k
            if (render_decorations_in_parent)
7549
22.9k
                window->DrawList = parent_window->DrawList;
7550
7551
            // Handle title bar, scrollbar, resize grips and resize borders
7552
300k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7553
300k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7554
300k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7555
7556
300k
            if (render_decorations_in_parent)
7557
22.9k
                window->DrawList = &window->DrawListInst;
7558
300k
        }
7559
7560
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7561
7562
        // Work rectangle.
7563
        // Affected by window padding and border size. Used by:
7564
        // - Columns() for right-most edge
7565
        // - TreeNode(), CollapsingHeader() for right-most edge
7566
        // - BeginTabBar() for right-most edge
7567
300k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7568
300k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7569
300k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7570
300k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7571
300k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7572
300k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7573
300k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7574
300k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7575
300k
        window->ParentWorkRect = window->WorkRect;
7576
7577
        // [LEGACY] Content Region
7578
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7579
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7580
        // Used by:
7581
        // - Mouse wheel scrolling + many other things
7582
300k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7583
300k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7584
300k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7585
300k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7586
7587
        // Setup drawing context
7588
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7589
300k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7590
300k
        window->DC.GroupOffset.x = 0.0f;
7591
300k
        window->DC.ColumnsOffset.x = 0.0f;
7592
7593
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7594
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7595
300k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7596
300k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7597
300k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7598
300k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7599
300k
        window->DC.CursorPos = window->DC.CursorStartPos;
7600
300k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7601
300k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7602
300k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7603
300k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7604
300k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7605
300k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7606
7607
300k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7608
300k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7609
300k
        window->DC.NavLayersActiveMaskNext = 0x00;
7610
300k
        window->DC.NavIsScrollPushableX = true;
7611
300k
        window->DC.NavHideHighlightOneFrame = false;
7612
300k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7613
7614
300k
        window->DC.MenuBarAppending = false;
7615
300k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7616
300k
        window->DC.TreeDepth = 0;
7617
300k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7618
300k
        window->DC.ChildWindows.resize(0);
7619
300k
        window->DC.StateStorage = &window->StateStorage;
7620
300k
        window->DC.CurrentColumns = NULL;
7621
300k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7622
300k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7623
7624
300k
        window->DC.ItemWidth = window->ItemWidthDefault;
7625
300k
        window->DC.TextWrapPos = -1.0f; // disabled
7626
300k
        window->DC.ItemWidthStack.resize(0);
7627
300k
        window->DC.TextWrapPosStack.resize(0);
7628
300k
        if (flags & ImGuiWindowFlags_Modal)
7629
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7630
7631
300k
        if (window->AutoFitFramesX > 0)
7632
2
            window->AutoFitFramesX--;
7633
300k
        if (window->AutoFitFramesY > 0)
7634
2
            window->AutoFitFramesY--;
7635
7636
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7637
300k
        g.NextWindowData.ClearFlags();
7638
7639
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7640
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7641
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7642
        // - Position window behind the modal that is not a begin-parent of this window.
7643
300k
        if (want_focus)
7644
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7645
300k
        if (want_focus && window == g.NavWindow)
7646
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7647
7648
        // Close requested by platform window (apply to all windows in this viewport)
7649
300k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7650
0
        {
7651
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7652
0
            *p_open = false;
7653
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7654
0
        }
7655
7656
        // Title bar
7657
300k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7658
277k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7659
7660
        // Clear hit test shape every frame
7661
300k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7662
7663
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7664
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7665
        // Maybe we can support CTRL+C on every element?
7666
        /*
7667
        //if (g.NavWindow == window && g.ActiveId == 0)
7668
        if (g.ActiveId == window->MoveId)
7669
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7670
                LogToClipboard();
7671
        */
7672
7673
300k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7674
300k
        {
7675
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7676
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7677
300k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7678
144
                BeginDockableDragDropSource(window);
7679
7680
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7681
300k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7682
196
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7683
101
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7684
101
                        BeginDockableDragDropTarget(window);
7685
300k
        }
7686
7687
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7688
        // This is useful to allow creating context menus on title bar only, etc.
7689
300k
        SetLastItemDataForWindow(window, title_bar_rect);
7690
7691
        // [DEBUG]
7692
300k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7693
300k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7694
0
            DebugLocateItemResolveWithLastItem();
7695
300k
#endif
7696
7697
        // [Test Engine] Register title bar / tab with MoveId.
7698
#ifdef IMGUI_ENABLE_TEST_ENGINE
7699
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7700
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7701
#endif
7702
300k
    }
7703
0
    else
7704
0
    {
7705
        // Skip refresh always mark active
7706
0
        if (window->SkipRefresh)
7707
0
            window->Active = true;
7708
7709
        // Append
7710
0
        SetCurrentViewport(window, window->Viewport);
7711
0
        SetCurrentWindow(window);
7712
0
        g.NextWindowData.ClearFlags();
7713
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7714
0
    }
7715
7716
300k
    if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
7717
300k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7718
7719
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7720
300k
    window->WriteAccessed = false;
7721
300k
    window->BeginCount++;
7722
7723
    // Update visibility
7724
300k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7725
300k
    {
7726
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7727
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7728
        // This is analogous to regular windows being hidden from one frame.
7729
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7730
300k
        if (window->DockIsActive && !window->DockTabIsVisible)
7731
0
        {
7732
0
            if (window->LastFrameJustFocused == g.FrameCount)
7733
0
                window->HiddenFramesCannotSkipItems = 1;
7734
0
            else
7735
0
                window->HiddenFramesCanSkipItems = 1;
7736
0
        }
7737
7738
300k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7739
22.9k
        {
7740
            // Child window can be out of sight and have "negative" clip windows.
7741
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7742
22.9k
            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7743
22.9k
            const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7744
22.9k
            if (!g.LogEnabled && !nav_request)
7745
22.9k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7746
19.8k
                {
7747
19.8k
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7748
0
                        window->HiddenFramesCannotSkipItems = 1;
7749
19.8k
                    else
7750
19.8k
                        window->HiddenFramesCanSkipItems = 1;
7751
19.8k
                }
7752
7753
            // Hide along with parent or if parent is collapsed
7754
22.9k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7755
0
                window->HiddenFramesCanSkipItems = 1;
7756
22.9k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7757
1
                window->HiddenFramesCannotSkipItems = 1;
7758
22.9k
        }
7759
7760
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7761
300k
        if (style.Alpha <= 0.0f)
7762
0
            window->HiddenFramesCanSkipItems = 1;
7763
7764
        // Update the Hidden flag
7765
300k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7766
300k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7767
7768
        // Disable inputs for requested number of frames
7769
300k
        if (window->DisableInputsFrames > 0)
7770
0
        {
7771
0
            window->DisableInputsFrames--;
7772
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7773
0
        }
7774
7775
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7776
300k
        bool skip_items = false;
7777
300k
        if (window->Collapsed || !window->Active || hidden_regular)
7778
135k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7779
135k
                skip_items = true;
7780
300k
        window->SkipItems = skip_items;
7781
7782
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7783
300k
        if (window->SkipItems)
7784
135k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7785
7786
        // Sanity check: there are two spots which can set Appearing = true
7787
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7788
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7789
300k
        if (window->SkipItems && !window->Appearing)
7790
300k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7791
300k
    }
7792
0
    else if (first_begin_of_the_frame)
7793
0
    {
7794
        // Skip refresh mode
7795
0
        window->SkipItems = true;
7796
0
    }
7797
7798
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7799
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7800
300k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7801
300k
    if (!window->IsFallbackWindow)
7802
161k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7803
0
        {
7804
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7805
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7806
0
            return false;
7807
0
        }
7808
300k
#endif
7809
7810
300k
    return !window->SkipItems;
7811
300k
}
7812
7813
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7814
300k
{
7815
300k
    ImGuiContext& g = *GImGui;
7816
300k
    if (window->DockIsActive)
7817
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7818
300k
    else
7819
300k
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7820
300k
}
7821
7822
void ImGui::End()
7823
300k
{
7824
300k
    ImGuiContext& g = *GImGui;
7825
300k
    ImGuiWindow* window = g.CurrentWindow;
7826
7827
    // Error checking: verify that user hasn't called End() too many times!
7828
300k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7829
0
    {
7830
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7831
0
        return;
7832
0
    }
7833
300k
    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7834
7835
    // Error checking: verify that user doesn't directly call End() on a child window.
7836
300k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7837
300k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7838
7839
    // Close anything that is open
7840
300k
    if (window->DC.CurrentColumns)
7841
0
        EndColumns();
7842
300k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)   // Pop inner window clip rectangle
7843
300k
        PopClipRect();
7844
300k
    PopFocusScope();
7845
300k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7846
0
        EndDisabledOverrideReenable();
7847
7848
300k
    if (window->SkipRefresh)
7849
0
    {
7850
0
        IM_ASSERT(window->DrawList == NULL);
7851
0
        window->DrawList = &window->DrawListInst;
7852
0
    }
7853
7854
    // Stop logging
7855
300k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7856
277k
        LogFinish();
7857
7858
300k
    if (window->DC.IsSetPos)
7859
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7860
7861
    // Docking: report contents sizes to parent to allow for auto-resize
7862
300k
    if (window->DockNode && window->DockTabIsVisible)
7863
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7864
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7865
7866
    // Pop from window stack
7867
300k
    g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7868
300k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7869
0
        g.BeginMenuDepth--;
7870
300k
    if (window->Flags & ImGuiWindowFlags_Popup)
7871
0
        g.BeginPopupStack.pop_back();
7872
300k
    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
7873
300k
    g.CurrentWindowStack.pop_back();
7874
300k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7875
300k
    if (g.CurrentWindow)
7876
161k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7877
300k
}
7878
7879
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7880
4.39k
{
7881
4.39k
    ImGuiContext& g = *GImGui;
7882
4.39k
    IM_ASSERT(window == window->RootWindow);
7883
7884
4.39k
    const int cur_order = window->FocusOrder;
7885
4.39k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7886
4.39k
    if (g.WindowsFocusOrder.back() == window)
7887
4.39k
        return;
7888
7889
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7890
0
    for (int n = cur_order; n < new_order; n++)
7891
0
    {
7892
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7893
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7894
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7895
0
    }
7896
0
    g.WindowsFocusOrder[new_order] = window;
7897
0
    window->FocusOrder = (short)new_order;
7898
0
}
7899
7900
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7901
4.39k
{
7902
4.39k
    ImGuiContext& g = *GImGui;
7903
4.39k
    ImGuiWindow* current_front_window = g.Windows.back();
7904
4.39k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7905
4.39k
        return;
7906
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7907
0
        if (g.Windows[i] == window)
7908
0
        {
7909
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7910
0
            g.Windows[g.Windows.Size - 1] = window;
7911
0
            break;
7912
0
        }
7913
0
}
7914
7915
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7916
0
{
7917
0
    ImGuiContext& g = *GImGui;
7918
0
    if (g.Windows[0] == window)
7919
0
        return;
7920
0
    for (int i = 0; i < g.Windows.Size; i++)
7921
0
        if (g.Windows[i] == window)
7922
0
        {
7923
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7924
0
            g.Windows[0] = window;
7925
0
            break;
7926
0
        }
7927
0
}
7928
7929
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7930
0
{
7931
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7932
0
    ImGuiContext& g = *GImGui;
7933
0
    window = window->RootWindow;
7934
0
    behind_window = behind_window->RootWindow;
7935
0
    int pos_wnd = FindWindowDisplayIndex(window);
7936
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7937
0
    if (pos_wnd < pos_beh)
7938
0
    {
7939
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7940
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7941
0
        g.Windows[pos_beh - 1] = window;
7942
0
    }
7943
0
    else
7944
0
    {
7945
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7946
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7947
0
        g.Windows[pos_beh] = window;
7948
0
    }
7949
0
}
7950
7951
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7952
0
{
7953
0
    ImGuiContext& g = *GImGui;
7954
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7955
0
}
7956
7957
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7958
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7959
18.4k
{
7960
18.4k
    ImGuiContext& g = *GImGui;
7961
7962
    // Modal check?
7963
18.4k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7964
172
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7965
0
        {
7966
            // This block would typically be reached in two situations:
7967
            // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
7968
            // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
7969
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7970
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7971
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
7972
0
            ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
7973
0
            return;
7974
0
        }
7975
7976
    // Find last focused child (if any) and focus it instead.
7977
18.4k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7978
2
        window = NavRestoreLastChildNavWindow(window);
7979
7980
    // Apply focus
7981
18.4k
    if (g.NavWindow != window)
7982
5.71k
    {
7983
5.71k
        SetNavWindow(window);
7984
5.71k
        if (window && g.NavDisableMouseHover)
7985
499
            g.NavMousePosDirty = true;
7986
5.71k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7987
5.71k
        g.NavLayer = ImGuiNavLayer_Main;
7988
5.71k
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7989
5.71k
        g.NavIdIsAlive = false;
7990
5.71k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7991
7992
        // Close popups if any
7993
5.71k
        ClosePopupsOverWindow(window, false);
7994
5.71k
    }
7995
7996
    // Move the root window to the top of the pile
7997
18.4k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7998
18.4k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7999
18.4k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
8000
18.4k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
8001
18.4k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
8002
8003
    // Steal active widgets. Some of the cases it triggers includes:
8004
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
8005
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
8006
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
8007
18.4k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
8008
52
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
8009
3
            ClearActiveID();
8010
8011
    // Passing NULL allow to disable keyboard focus
8012
18.4k
    if (!window)
8013
14.0k
        return;
8014
4.39k
    window->LastFrameJustFocused = g.FrameCount;
8015
8016
    // Select in dock node
8017
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
8018
    //if (dock_node && dock_node->TabBar)
8019
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
8020
8021
    // Bring to front
8022
4.39k
    BringWindowToFocusFront(focus_front_window);
8023
4.39k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8024
4.39k
        BringWindowToDisplayFront(display_front_window);
8025
4.39k
}
8026
8027
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
8028
2
{
8029
2
    ImGuiContext& g = *GImGui;
8030
2
    int start_idx = g.WindowsFocusOrder.Size - 1;
8031
2
    if (under_this_window != NULL)
8032
0
    {
8033
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
8034
0
        int offset = -1;
8035
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
8036
0
        {
8037
0
            under_this_window = under_this_window->ParentWindow;
8038
0
            offset = 0;
8039
0
        }
8040
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
8041
0
    }
8042
2
    for (int i = start_idx; i >= 0; i--)
8043
2
    {
8044
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
8045
2
        ImGuiWindow* window = g.WindowsFocusOrder[i];
8046
2
        if (window == ignore_window || !window->WasActive)
8047
0
            continue;
8048
2
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
8049
0
            continue;
8050
2
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
8051
2
        {
8052
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
8053
            // This is failing (lagging by one frame) for docked windows.
8054
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
8055
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
8056
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
8057
2
            FocusWindow(window, flags);
8058
2
            return;
8059
2
        }
8060
2
    }
8061
0
    FocusWindow(NULL, flags);
8062
0
}
8063
8064
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
8065
void ImGui::SetCurrentFont(ImFont* font)
8066
138k
{
8067
138k
    ImGuiContext& g = *GImGui;
8068
138k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
8069
138k
    IM_ASSERT(font->Scale > 0.0f);
8070
138k
    g.Font = font;
8071
138k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
8072
138k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
8073
8074
138k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
8075
138k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
8076
138k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
8077
138k
    g.DrawListSharedData.Font = g.Font;
8078
138k
    g.DrawListSharedData.FontSize = g.FontSize;
8079
138k
}
8080
8081
void ImGui::PushFont(ImFont* font)
8082
0
{
8083
0
    ImGuiContext& g = *GImGui;
8084
0
    if (!font)
8085
0
        font = GetDefaultFont();
8086
0
    SetCurrentFont(font);
8087
0
    g.FontStack.push_back(font);
8088
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
8089
0
}
8090
8091
void  ImGui::PopFont()
8092
0
{
8093
0
    ImGuiContext& g = *GImGui;
8094
0
    g.CurrentWindow->DrawList->PopTextureID();
8095
0
    g.FontStack.pop_back();
8096
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
8097
0
}
8098
8099
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8100
22.9k
{
8101
22.9k
    ImGuiContext& g = *GImGui;
8102
22.9k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
8103
22.9k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8104
22.9k
    if (enabled)
8105
0
        item_flags |= option;
8106
22.9k
    else
8107
22.9k
        item_flags &= ~option;
8108
22.9k
    g.CurrentItemFlags = item_flags;
8109
22.9k
    g.ItemFlagsStack.push_back(item_flags);
8110
22.9k
}
8111
8112
void ImGui::PopItemFlag()
8113
22.9k
{
8114
22.9k
    ImGuiContext& g = *GImGui;
8115
22.9k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
8116
22.9k
    g.ItemFlagsStack.pop_back();
8117
22.9k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8118
22.9k
}
8119
8120
// BeginDisabled()/EndDisabled()
8121
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8122
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8123
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8124
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
8125
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
8126
void ImGui::BeginDisabled(bool disabled)
8127
0
{
8128
0
    ImGuiContext& g = *GImGui;
8129
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8130
0
    if (!was_disabled && disabled)
8131
0
    {
8132
0
        g.DisabledAlphaBackup = g.Style.Alpha;
8133
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8134
0
    }
8135
0
    if (was_disabled || disabled)
8136
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8137
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8138
0
    g.DisabledStackSize++;
8139
0
}
8140
8141
void ImGui::EndDisabled()
8142
0
{
8143
0
    ImGuiContext& g = *GImGui;
8144
0
    IM_ASSERT(g.DisabledStackSize > 0);
8145
0
    g.DisabledStackSize--;
8146
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8147
    //PopItemFlag();
8148
0
    g.ItemFlagsStack.pop_back();
8149
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8150
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8151
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8152
0
}
8153
8154
// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8155
// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8156
// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8157
void ImGui::BeginDisabledOverrideReenable()
8158
0
{
8159
0
    ImGuiContext& g = *GImGui;
8160
0
    IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8161
0
    g.Style.Alpha = g.DisabledAlphaBackup;
8162
0
    g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8163
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8164
0
    g.DisabledStackSize++;
8165
0
}
8166
8167
void ImGui::EndDisabledOverrideReenable()
8168
0
{
8169
0
    ImGuiContext& g = *GImGui;
8170
0
    g.DisabledStackSize--;
8171
0
    IM_ASSERT(g.DisabledStackSize > 0);
8172
0
    g.ItemFlagsStack.pop_back();
8173
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8174
0
    g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8175
0
}
8176
8177
void ImGui::PushTabStop(bool tab_stop)
8178
22.9k
{
8179
22.9k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
8180
22.9k
}
8181
8182
void ImGui::PopTabStop()
8183
22.9k
{
8184
22.9k
    PopItemFlag();
8185
22.9k
}
8186
8187
void ImGui::PushButtonRepeat(bool repeat)
8188
0
{
8189
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
8190
0
}
8191
8192
void ImGui::PopButtonRepeat()
8193
0
{
8194
0
    PopItemFlag();
8195
0
}
8196
8197
void ImGui::PushTextWrapPos(float wrap_pos_x)
8198
0
{
8199
0
    ImGuiWindow* window = GetCurrentWindow();
8200
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8201
0
    window->DC.TextWrapPos = wrap_pos_x;
8202
0
}
8203
8204
void ImGui::PopTextWrapPos()
8205
0
{
8206
0
    ImGuiWindow* window = GetCurrentWindow();
8207
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8208
0
    window->DC.TextWrapPosStack.pop_back();
8209
0
}
8210
8211
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8212
0
{
8213
0
    ImGuiWindow* last_window = NULL;
8214
0
    while (last_window != window)
8215
0
    {
8216
0
        last_window = window;
8217
0
        window = window->RootWindow;
8218
0
        if (popup_hierarchy)
8219
0
            window = window->RootWindowPopupTree;
8220
0
    if (dock_hierarchy)
8221
0
      window = window->RootWindowDockTree;
8222
0
  }
8223
0
    return window;
8224
0
}
8225
8226
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8227
0
{
8228
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8229
0
    if (window_root == potential_parent)
8230
0
        return true;
8231
0
    while (window != NULL)
8232
0
    {
8233
0
        if (window == potential_parent)
8234
0
            return true;
8235
0
        if (window == window_root) // end of chain
8236
0
            return false;
8237
0
        window = window->ParentWindow;
8238
0
    }
8239
0
    return false;
8240
0
}
8241
8242
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8243
0
{
8244
0
    if (window->RootWindow == potential_parent)
8245
0
        return true;
8246
0
    while (window != NULL)
8247
0
    {
8248
0
        if (window == potential_parent)
8249
0
            return true;
8250
0
        window = window->ParentWindowInBeginStack;
8251
0
    }
8252
0
    return false;
8253
0
}
8254
8255
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8256
0
{
8257
0
    ImGuiContext& g = *GImGui;
8258
8259
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8260
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8261
0
    if (display_layer_delta != 0)
8262
0
        return display_layer_delta > 0;
8263
8264
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8265
0
    {
8266
0
        ImGuiWindow* candidate_window = g.Windows[i];
8267
0
        if (candidate_window == potential_above)
8268
0
            return true;
8269
0
        if (candidate_window == potential_below)
8270
0
            return false;
8271
0
    }
8272
0
    return false;
8273
0
}
8274
8275
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8276
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8277
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8278
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8279
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8280
30.1k
{
8281
30.1k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8282
8283
30.1k
    ImGuiContext& g = *GImGui;
8284
30.1k
    ImGuiWindow* ref_window = g.HoveredWindow;
8285
30.1k
    ImGuiWindow* cur_window = g.CurrentWindow;
8286
30.1k
    if (ref_window == NULL)
8287
29.3k
        return false;
8288
8289
759
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8290
759
    {
8291
759
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8292
759
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8293
759
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8294
759
        if (flags & ImGuiHoveredFlags_RootWindow)
8295
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8296
8297
759
        bool result;
8298
759
        if (flags & ImGuiHoveredFlags_ChildWindows)
8299
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8300
759
        else
8301
759
            result = (ref_window == cur_window);
8302
759
        if (!result)
8303
733
            return false;
8304
759
    }
8305
8306
26
    if (!IsWindowContentHoverable(ref_window, flags))
8307
0
        return false;
8308
26
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8309
26
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8310
0
            return false;
8311
8312
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8313
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8314
    // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8315
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8316
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8317
26
    if (flags & ImGuiHoveredFlags_ForTooltip)
8318
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8319
26
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8320
0
        return false;
8321
8322
26
    return true;
8323
26
}
8324
8325
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8326
44.1k
{
8327
44.1k
    ImGuiContext& g = *GImGui;
8328
44.1k
    ImGuiWindow* ref_window = g.NavWindow;
8329
44.1k
    ImGuiWindow* cur_window = g.CurrentWindow;
8330
8331
44.1k
    if (ref_window == NULL)
8332
29.6k
        return false;
8333
14.4k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8334
0
        return true;
8335
8336
14.4k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8337
14.4k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8338
14.4k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8339
14.4k
    if (flags & ImGuiHoveredFlags_RootWindow)
8340
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8341
8342
14.4k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8343
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8344
14.4k
    else
8345
14.4k
        return (ref_window == cur_window);
8346
14.4k
}
8347
8348
ImGuiID ImGui::GetWindowDockID()
8349
0
{
8350
0
    ImGuiContext& g = *GImGui;
8351
0
    return g.CurrentWindow->DockId;
8352
0
}
8353
8354
bool ImGui::IsWindowDocked()
8355
0
{
8356
0
    ImGuiContext& g = *GImGui;
8357
0
    return g.CurrentWindow->DockIsActive;
8358
0
}
8359
8360
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8361
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8362
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8363
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8364
0
{
8365
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8366
0
}
8367
8368
float ImGui::GetWindowWidth()
8369
4.01k
{
8370
4.01k
    ImGuiWindow* window = GImGui->CurrentWindow;
8371
4.01k
    return window->Size.x;
8372
4.01k
}
8373
8374
float ImGui::GetWindowHeight()
8375
4.05k
{
8376
4.05k
    ImGuiWindow* window = GImGui->CurrentWindow;
8377
4.05k
    return window->Size.y;
8378
4.05k
}
8379
8380
ImVec2 ImGui::GetWindowPos()
8381
0
{
8382
0
    ImGuiContext& g = *GImGui;
8383
0
    ImGuiWindow* window = g.CurrentWindow;
8384
0
    return window->Pos;
8385
0
}
8386
8387
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8388
4
{
8389
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8390
4
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8391
0
        return;
8392
8393
4
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8394
4
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8395
4
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8396
8397
    // Set
8398
4
    const ImVec2 old_pos = window->Pos;
8399
4
    window->Pos = ImTrunc(pos);
8400
4
    ImVec2 offset = window->Pos - old_pos;
8401
4
    if (offset.x == 0.0f && offset.y == 0.0f)
8402
0
        return;
8403
4
    MarkIniSettingsDirty(window);
8404
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8405
4
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8406
4
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8407
4
    window->DC.IdealMaxPos += offset;
8408
4
    window->DC.CursorStartPos += offset;
8409
4
}
8410
8411
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8412
0
{
8413
0
    ImGuiWindow* window = GetCurrentWindowRead();
8414
0
    SetWindowPos(window, pos, cond);
8415
0
}
8416
8417
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8418
0
{
8419
0
    if (ImGuiWindow* window = FindWindowByName(name))
8420
0
        SetWindowPos(window, pos, cond);
8421
0
}
8422
8423
ImVec2 ImGui::GetWindowSize()
8424
0
{
8425
0
    ImGuiWindow* window = GetCurrentWindowRead();
8426
0
    return window->Size;
8427
0
}
8428
8429
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8430
161k
{
8431
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8432
161k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8433
138k
        return;
8434
8435
22.9k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8436
22.9k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8437
8438
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8439
22.9k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8440
4
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8441
22.9k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8442
4
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8443
8444
    // Set
8445
22.9k
    ImVec2 old_size = window->SizeFull;
8446
22.9k
    if (size.x <= 0.0f)
8447
0
        window->AutoFitOnlyGrows = false;
8448
22.9k
    else
8449
22.9k
        window->SizeFull.x = IM_TRUNC(size.x);
8450
22.9k
    if (size.y <= 0.0f)
8451
0
        window->AutoFitOnlyGrows = false;
8452
22.9k
    else
8453
22.9k
        window->SizeFull.y = IM_TRUNC(size.y);
8454
22.9k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8455
22.7k
        MarkIniSettingsDirty(window);
8456
22.9k
}
8457
8458
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8459
0
{
8460
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8461
0
}
8462
8463
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8464
0
{
8465
0
    if (ImGuiWindow* window = FindWindowByName(name))
8466
0
        SetWindowSize(window, size, cond);
8467
0
}
8468
8469
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8470
0
{
8471
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8472
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8473
0
        return;
8474
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8475
8476
    // Set
8477
0
    window->Collapsed = collapsed;
8478
0
}
8479
8480
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8481
0
{
8482
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8483
0
    window->HitTestHoleSize = ImVec2ih(size);
8484
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8485
0
}
8486
8487
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8488
0
{
8489
0
    window->Hidden = window->SkipItems = true;
8490
0
    window->HiddenFramesCanSkipItems = 1;
8491
0
}
8492
8493
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8494
0
{
8495
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8496
0
}
8497
8498
bool ImGui::IsWindowCollapsed()
8499
0
{
8500
0
    ImGuiWindow* window = GetCurrentWindowRead();
8501
0
    return window->Collapsed;
8502
0
}
8503
8504
bool ImGui::IsWindowAppearing()
8505
0
{
8506
0
    ImGuiWindow* window = GetCurrentWindowRead();
8507
0
    return window->Appearing;
8508
0
}
8509
8510
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8511
0
{
8512
0
    if (ImGuiWindow* window = FindWindowByName(name))
8513
0
        SetWindowCollapsed(window, collapsed, cond);
8514
0
}
8515
8516
void ImGui::SetWindowFocus()
8517
4.01k
{
8518
4.01k
    FocusWindow(GImGui->CurrentWindow);
8519
4.01k
}
8520
8521
void ImGui::SetWindowFocus(const char* name)
8522
0
{
8523
0
    if (name)
8524
0
    {
8525
0
        if (ImGuiWindow* window = FindWindowByName(name))
8526
0
            FocusWindow(window);
8527
0
    }
8528
0
    else
8529
0
    {
8530
0
        FocusWindow(NULL);
8531
0
    }
8532
0
}
8533
8534
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8535
0
{
8536
0
    ImGuiContext& g = *GImGui;
8537
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8538
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8539
0
    g.NextWindowData.PosVal = pos;
8540
0
    g.NextWindowData.PosPivotVal = pivot;
8541
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8542
0
    g.NextWindowData.PosUndock = true;
8543
0
}
8544
8545
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8546
161k
{
8547
161k
    ImGuiContext& g = *GImGui;
8548
161k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8549
161k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8550
161k
    g.NextWindowData.SizeVal = size;
8551
161k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8552
161k
}
8553
8554
// For each axis:
8555
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8556
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8557
// - See "Demo->Examples->Constrained-resizing window" for examples.
8558
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8559
0
{
8560
0
    ImGuiContext& g = *GImGui;
8561
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8562
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8563
0
    g.NextWindowData.SizeCallback = custom_callback;
8564
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8565
0
}
8566
8567
// Content size = inner scrollable rectangle, padded with WindowPadding.
8568
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8569
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8570
0
{
8571
0
    ImGuiContext& g = *GImGui;
8572
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8573
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8574
0
}
8575
8576
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8577
0
{
8578
0
    ImGuiContext& g = *GImGui;
8579
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8580
0
    g.NextWindowData.ScrollVal = scroll;
8581
0
}
8582
8583
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8584
0
{
8585
0
    ImGuiContext& g = *GImGui;
8586
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8587
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8588
0
    g.NextWindowData.CollapsedVal = collapsed;
8589
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8590
0
}
8591
8592
void ImGui::SetNextWindowFocus()
8593
0
{
8594
0
    ImGuiContext& g = *GImGui;
8595
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8596
0
}
8597
8598
void ImGui::SetNextWindowBgAlpha(float alpha)
8599
0
{
8600
0
    ImGuiContext& g = *GImGui;
8601
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8602
0
    g.NextWindowData.BgAlphaVal = alpha;
8603
0
}
8604
8605
void ImGui::SetNextWindowViewport(ImGuiID id)
8606
0
{
8607
0
    ImGuiContext& g = *GImGui;
8608
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8609
0
    g.NextWindowData.ViewportId = id;
8610
0
}
8611
8612
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8613
0
{
8614
0
    ImGuiContext& g = *GImGui;
8615
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8616
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8617
0
    g.NextWindowData.DockId = id;
8618
0
}
8619
8620
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8621
0
{
8622
0
    ImGuiContext& g = *GImGui;
8623
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8624
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8625
0
    g.NextWindowData.WindowClass = *window_class;
8626
0
}
8627
8628
// This is experimental and meant to be a toy for exploring a future/wider range of features.
8629
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8630
0
{
8631
0
    ImGuiContext& g = *GImGui;
8632
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8633
0
    g.NextWindowData.RefreshFlagsVal = flags;
8634
0
}
8635
8636
ImDrawList* ImGui::GetWindowDrawList()
8637
22.9k
{
8638
22.9k
    ImGuiWindow* window = GetCurrentWindow();
8639
22.9k
    return window->DrawList;
8640
22.9k
}
8641
8642
float ImGui::GetWindowDpiScale()
8643
0
{
8644
0
    ImGuiContext& g = *GImGui;
8645
0
    return g.CurrentDpiScale;
8646
0
}
8647
8648
ImGuiViewport* ImGui::GetWindowViewport()
8649
0
{
8650
0
    ImGuiContext& g = *GImGui;
8651
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8652
0
    return g.CurrentViewport;
8653
0
}
8654
8655
ImFont* ImGui::GetFont()
8656
2.02M
{
8657
2.02M
    return GImGui->Font;
8658
2.02M
}
8659
8660
float ImGui::GetFontSize()
8661
2.02M
{
8662
2.02M
    return GImGui->FontSize;
8663
2.02M
}
8664
8665
ImVec2 ImGui::GetFontTexUvWhitePixel()
8666
0
{
8667
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8668
0
}
8669
8670
void ImGui::SetWindowFontScale(float scale)
8671
0
{
8672
0
    IM_ASSERT(scale > 0.0f);
8673
0
    ImGuiContext& g = *GImGui;
8674
0
    ImGuiWindow* window = GetCurrentWindow();
8675
0
    window->FontWindowScale = scale;
8676
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8677
0
}
8678
8679
void ImGui::PushFocusScope(ImGuiID id)
8680
300k
{
8681
300k
    ImGuiContext& g = *GImGui;
8682
300k
    ImGuiFocusScopeData data;
8683
300k
    data.ID = id;
8684
300k
    data.WindowID = g.CurrentWindow->ID;
8685
300k
    g.FocusScopeStack.push_back(data);
8686
300k
    g.CurrentFocusScopeId = id;
8687
300k
}
8688
8689
void ImGui::PopFocusScope()
8690
300k
{
8691
300k
    ImGuiContext& g = *GImGui;
8692
300k
    if (g.FocusScopeStack.Size == 0)
8693
0
    {
8694
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8695
0
        return;
8696
0
    }
8697
300k
    g.FocusScopeStack.pop_back();
8698
300k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8699
300k
}
8700
8701
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8702
6.37k
{
8703
6.37k
    ImGuiContext& g = *GImGui;
8704
6.37k
    g.NavFocusScopeId = focus_scope_id;
8705
6.37k
    g.NavFocusRoute.resize(0); // Invalidate
8706
6.37k
    if (focus_scope_id == 0)
8707
2.87k
        return;
8708
3.50k
    IM_ASSERT(g.NavWindow != NULL);
8709
8710
    // Store current path (in reverse order)
8711
3.50k
    if (focus_scope_id == g.CurrentFocusScopeId)
8712
3.02k
    {
8713
        // Top of focus stack contains local focus scopes inside current window
8714
6.05k
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8715
3.02k
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8716
3.02k
    }
8717
473
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8718
469
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8719
4
    else
8720
4
        return;
8721
8722
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8723
6.24k
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8724
2.75k
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8725
3.49k
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8726
3.49k
}
8727
8728
// Focus = move navigation cursor, set scrolling, set focus window.
8729
void ImGui::FocusItem()
8730
0
{
8731
0
    ImGuiContext& g = *GImGui;
8732
0
    ImGuiWindow* window = g.CurrentWindow;
8733
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8734
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8735
0
    {
8736
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8737
0
        return;
8738
0
    }
8739
8740
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8741
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8742
0
    SetNavWindow(window);
8743
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8744
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8745
0
}
8746
8747
void ImGui::ActivateItemByID(ImGuiID id)
8748
0
{
8749
0
    ImGuiContext& g = *GImGui;
8750
0
    g.NavNextActivateId = id;
8751
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8752
0
}
8753
8754
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8755
// But ActivateItem() should function without altering scroll/focus?
8756
void ImGui::SetKeyboardFocusHere(int offset)
8757
0
{
8758
0
    ImGuiContext& g = *GImGui;
8759
0
    ImGuiWindow* window = g.CurrentWindow;
8760
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8761
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8762
8763
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8764
    // When we refactor this function into ActivateItem() we may want to make this an option.
8765
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8766
    // is also automatically dropped in the event g.ActiveId is stolen.
8767
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8768
0
    {
8769
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8770
0
        return;
8771
0
    }
8772
8773
0
    SetNavWindow(window);
8774
8775
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8776
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8777
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8778
0
    if (offset == -1)
8779
0
    {
8780
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8781
0
    }
8782
0
    else
8783
0
    {
8784
0
        g.NavTabbingDir = 1;
8785
0
        g.NavTabbingCounter = offset + 1;
8786
0
    }
8787
0
}
8788
8789
void ImGui::SetItemDefaultFocus()
8790
0
{
8791
0
    ImGuiContext& g = *GImGui;
8792
0
    ImGuiWindow* window = g.CurrentWindow;
8793
0
    if (!window->Appearing)
8794
0
        return;
8795
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8796
0
        return;
8797
8798
0
    g.NavInitRequest = false;
8799
0
    NavApplyItemToResult(&g.NavInitResult);
8800
0
    NavUpdateAnyRequestFlag();
8801
8802
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8803
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8804
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8805
0
}
8806
8807
void ImGui::SetStateStorage(ImGuiStorage* tree)
8808
0
{
8809
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8810
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8811
0
}
8812
8813
ImGuiStorage* ImGui::GetStateStorage()
8814
0
{
8815
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8816
0
    return window->DC.StateStorage;
8817
0
}
8818
8819
bool ImGui::IsRectVisible(const ImVec2& size)
8820
0
{
8821
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8822
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8823
0
}
8824
8825
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8826
0
{
8827
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8828
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8829
0
}
8830
8831
//-----------------------------------------------------------------------------
8832
// [SECTION] ID STACK
8833
//-----------------------------------------------------------------------------
8834
8835
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8836
// it should ideally be flattened at some point but it's been used a lots by widgets.
8837
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8838
365k
{
8839
365k
    ImGuiID seed = IDStack.back();
8840
365k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8841
365k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8842
365k
    ImGuiContext& g = *Ctx;
8843
365k
    if (g.DebugHookIdInfo == id)
8844
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8845
365k
#endif
8846
365k
    return id;
8847
365k
}
8848
8849
ImGuiID ImGuiWindow::GetID(const void* ptr)
8850
0
{
8851
0
    ImGuiID seed = IDStack.back();
8852
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8853
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8854
0
    ImGuiContext& g = *Ctx;
8855
0
    if (g.DebugHookIdInfo == id)
8856
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8857
0
#endif
8858
0
    return id;
8859
0
}
8860
8861
ImGuiID ImGuiWindow::GetID(int n)
8862
137k
{
8863
137k
    ImGuiID seed = IDStack.back();
8864
137k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8865
137k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8866
137k
    ImGuiContext& g = *Ctx;
8867
137k
    if (g.DebugHookIdInfo == id)
8868
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8869
137k
#endif
8870
137k
    return id;
8871
137k
}
8872
8873
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8874
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8875
0
{
8876
0
    ImGuiID seed = IDStack.back();
8877
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8878
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8879
0
    return id;
8880
0
}
8881
8882
void ImGui::PushID(const char* str_id)
8883
22.9k
{
8884
22.9k
    ImGuiContext& g = *GImGui;
8885
22.9k
    ImGuiWindow* window = g.CurrentWindow;
8886
22.9k
    ImGuiID id = window->GetID(str_id);
8887
22.9k
    window->IDStack.push_back(id);
8888
22.9k
}
8889
8890
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8891
0
{
8892
0
    ImGuiContext& g = *GImGui;
8893
0
    ImGuiWindow* window = g.CurrentWindow;
8894
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8895
0
    window->IDStack.push_back(id);
8896
0
}
8897
8898
void ImGui::PushID(const void* ptr_id)
8899
0
{
8900
0
    ImGuiContext& g = *GImGui;
8901
0
    ImGuiWindow* window = g.CurrentWindow;
8902
0
    ImGuiID id = window->GetID(ptr_id);
8903
0
    window->IDStack.push_back(id);
8904
0
}
8905
8906
void ImGui::PushID(int int_id)
8907
0
{
8908
0
    ImGuiContext& g = *GImGui;
8909
0
    ImGuiWindow* window = g.CurrentWindow;
8910
0
    ImGuiID id = window->GetID(int_id);
8911
0
    window->IDStack.push_back(id);
8912
0
}
8913
8914
// Push a given id value ignoring the ID stack as a seed.
8915
void ImGui::PushOverrideID(ImGuiID id)
8916
0
{
8917
0
    ImGuiContext& g = *GImGui;
8918
0
    ImGuiWindow* window = g.CurrentWindow;
8919
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8920
0
    if (g.DebugHookIdInfo == id)
8921
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8922
0
#endif
8923
0
    window->IDStack.push_back(id);
8924
0
}
8925
8926
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8927
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8928
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8929
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8930
0
{
8931
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8932
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8933
0
    ImGuiContext& g = *GImGui;
8934
0
    if (g.DebugHookIdInfo == id)
8935
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8936
0
#endif
8937
0
    return id;
8938
0
}
8939
8940
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8941
0
{
8942
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8943
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8944
0
    ImGuiContext& g = *GImGui;
8945
0
    if (g.DebugHookIdInfo == id)
8946
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8947
0
#endif
8948
0
    return id;
8949
0
}
8950
8951
void ImGui::PopID()
8952
22.9k
{
8953
22.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
8954
22.9k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8955
22.9k
    window->IDStack.pop_back();
8956
22.9k
}
8957
8958
ImGuiID ImGui::GetID(const char* str_id)
8959
0
{
8960
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8961
0
    return window->GetID(str_id);
8962
0
}
8963
8964
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8965
0
{
8966
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8967
0
    return window->GetID(str_id_begin, str_id_end);
8968
0
}
8969
8970
ImGuiID ImGui::GetID(const void* ptr_id)
8971
0
{
8972
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8973
0
    return window->GetID(ptr_id);
8974
0
}
8975
8976
//-----------------------------------------------------------------------------
8977
// [SECTION] INPUTS
8978
//-----------------------------------------------------------------------------
8979
// - GetModForModKey() [Internal]
8980
// - FixupKeyChord() [Internal]
8981
// - GetKeyData() [Internal]
8982
// - GetKeyIndex() [Internal]
8983
// - GetKeyName()
8984
// - GetKeyChordName() [Internal]
8985
// - CalcTypematicRepeatAmount() [Internal]
8986
// - GetTypematicRepeatRate() [Internal]
8987
// - GetKeyPressedAmount() [Internal]
8988
// - GetKeyMagnitude2d() [Internal]
8989
//-----------------------------------------------------------------------------
8990
// - UpdateKeyRoutingTable() [Internal]
8991
// - GetRoutingIdFromOwnerId() [Internal]
8992
// - GetShortcutRoutingData() [Internal]
8993
// - CalcRoutingScore() [Internal]
8994
// - SetShortcutRouting() [Internal]
8995
// - TestShortcutRouting() [Internal]
8996
//-----------------------------------------------------------------------------
8997
// - IsKeyDown()
8998
// - IsKeyPressed()
8999
// - IsKeyReleased()
9000
//-----------------------------------------------------------------------------
9001
// - IsMouseDown()
9002
// - IsMouseClicked()
9003
// - IsMouseReleased()
9004
// - IsMouseDoubleClicked()
9005
// - GetMouseClickedCount()
9006
// - IsMouseHoveringRect() [Internal]
9007
// - IsMouseDragPastThreshold() [Internal]
9008
// - IsMouseDragging()
9009
// - GetMousePos()
9010
// - SetMousePos() [Internal]
9011
// - GetMousePosOnOpeningCurrentPopup()
9012
// - IsMousePosValid()
9013
// - IsAnyMouseDown()
9014
// - GetMouseDragDelta()
9015
// - ResetMouseDragDelta()
9016
// - GetMouseCursor()
9017
// - SetMouseCursor()
9018
//-----------------------------------------------------------------------------
9019
// - UpdateAliasKey()
9020
// - GetMergedModsFromKeys()
9021
// - UpdateKeyboardInputs()
9022
// - UpdateMouseInputs()
9023
//-----------------------------------------------------------------------------
9024
// - LockWheelingWindow [Internal]
9025
// - FindBestWheelingWindow [Internal]
9026
// - UpdateMouseWheel() [Internal]
9027
//-----------------------------------------------------------------------------
9028
// - SetNextFrameWantCaptureKeyboard()
9029
// - SetNextFrameWantCaptureMouse()
9030
//-----------------------------------------------------------------------------
9031
// - GetInputSourceName() [Internal]
9032
// - DebugPrintInputEvent() [Internal]
9033
// - UpdateInputEvents() [Internal]
9034
//-----------------------------------------------------------------------------
9035
// - GetKeyOwner() [Internal]
9036
// - TestKeyOwner() [Internal]
9037
// - SetKeyOwner() [Internal]
9038
// - SetItemKeyOwner() [Internal]
9039
// - Shortcut() [Internal]
9040
//-----------------------------------------------------------------------------
9041
9042
static ImGuiKeyChord GetModForModKey(ImGuiKey key)
9043
0
{
9044
0
    if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9045
0
        return ImGuiMod_Ctrl;
9046
0
    if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9047
0
        return ImGuiMod_Shift;
9048
0
    if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9049
0
        return ImGuiMod_Alt;
9050
0
    if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9051
0
        return ImGuiMod_Super;
9052
0
    return ImGuiMod_None;
9053
0
}
9054
9055
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9056
555k
{
9057
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9058
555k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9059
555k
    if (IsModKey(key))
9060
0
        key_chord |= GetModForModKey(key);
9061
555k
    return key_chord;
9062
555k
}
9063
9064
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9065
3.68M
{
9066
3.68M
    ImGuiContext& g = *ctx;
9067
9068
    // Special storage location for mods
9069
3.68M
    if (key & ImGuiMod_Mask_)
9070
1.11M
        key = ConvertSingleModFlagToKey(key);
9071
9072
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9073
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
9074
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
9075
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
9076
#else
9077
3.68M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9078
3.68M
#endif
9079
3.68M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
9080
3.68M
}
9081
9082
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9083
// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
9084
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
9085
{
9086
    ImGuiContext& g = *GImGui;
9087
    IM_ASSERT(IsNamedKey(key));
9088
    const ImGuiKeyData* key_data = GetKeyData(key);
9089
    return (ImGuiKey)(key_data - g.IO.KeysData);
9090
}
9091
#endif
9092
9093
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
9094
static const char* const GKeyNames[] =
9095
{
9096
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9097
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9098
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9099
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9100
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9101
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9102
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9103
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9104
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9105
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9106
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9107
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9108
    "AppBack", "AppForward",
9109
    "GamepadStart", "GamepadBack",
9110
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9111
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9112
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9113
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9114
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9115
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9116
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9117
};
9118
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9119
9120
const char* ImGui::GetKeyName(ImGuiKey key)
9121
0
{
9122
0
    if (key == ImGuiKey_None)
9123
0
        return "None";
9124
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
9125
0
    IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9126
#else
9127
    ImGuiContext& g = *GImGui;
9128
    if (IsLegacyKey(key))
9129
    {
9130
        if (g.IO.KeyMap[key] == -1)
9131
            return "N/A";
9132
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
9133
        key = (ImGuiKey)g.IO.KeyMap[key];
9134
    }
9135
#endif
9136
0
    if (key & ImGuiMod_Mask_)
9137
0
        key = ConvertSingleModFlagToKey(key);
9138
0
    if (!IsNamedKey(key))
9139
0
        return "Unknown";
9140
9141
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9142
0
}
9143
9144
// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9145
// Lifetime of return value: valid until next call to same function.
9146
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9147
0
{
9148
0
    ImGuiContext& g = *GImGui;
9149
9150
0
    const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9151
0
    if (IsModKey(key))
9152
0
        key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9153
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9154
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9155
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9156
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9157
0
        (key_chord & ImGuiMod_Super) ? "Super+" : "",
9158
0
        (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9159
0
    size_t len;
9160
0
    if (key == ImGuiKey_None && key_chord != 0)
9161
0
        if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9162
0
            g.TempKeychordName[len - 1] = 0;
9163
0
    return g.TempKeychordName;
9164
0
}
9165
9166
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9167
// t1 = current time (e.g.: g.Time)
9168
// An event is triggered at:
9169
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
9170
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9171
2.60k
{
9172
2.60k
    if (t1 == 0.0f)
9173
0
        return 1;
9174
2.60k
    if (t0 >= t1)
9175
0
        return 0;
9176
2.60k
    if (repeat_rate <= 0.0f)
9177
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
9178
2.60k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9179
2.60k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9180
2.60k
    const int count = count_t1 - count_t0;
9181
2.60k
    return count;
9182
2.60k
}
9183
9184
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9185
8.69k
{
9186
8.69k
    ImGuiContext& g = *GImGui;
9187
8.69k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
9188
8.69k
    {
9189
2.90k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9190
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9191
5.78k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9192
8.69k
    }
9193
8.69k
}
9194
9195
// Return value representing the number of presses in the last time period, for the given repeat rate
9196
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9197
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9198
2.60k
{
9199
2.60k
    ImGuiContext& g = *GImGui;
9200
2.60k
    const ImGuiKeyData* key_data = GetKeyData(key);
9201
2.60k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9202
0
        return 0;
9203
2.60k
    const float t = key_data->DownDuration;
9204
2.60k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9205
2.60k
}
9206
9207
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9208
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9209
0
{
9210
0
    return ImVec2(
9211
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9212
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9213
0
}
9214
9215
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9216
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
9217
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
9218
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9219
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9220
138k
{
9221
138k
    ImGuiContext& g = *GImGui;
9222
138k
    rt->EntriesNext.resize(0);
9223
21.5M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9224
21.3M
    {
9225
21.3M
        const int new_routing_start_idx = rt->EntriesNext.Size;
9226
21.3M
        ImGuiKeyRoutingData* routing_entry;
9227
21.3M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9228
0
        {
9229
0
            routing_entry = &rt->Entries[old_routing_idx];
9230
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9231
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9232
0
            routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9233
0
            routing_entry->RoutingNextScore = 255;
9234
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9235
0
                continue;
9236
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9237
9238
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9239
            // This is the result of previous frame's SetShortcutRouting() call.
9240
0
            if (routing_entry->Mods == g.IO.KeyMods)
9241
0
            {
9242
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9243
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9244
0
                {
9245
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9246
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9247
0
                }
9248
0
            }
9249
0
        }
9250
9251
        // Rewrite linked-list
9252
21.3M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9253
21.3M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9254
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9255
21.3M
    }
9256
138k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9257
138k
}
9258
9259
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9260
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9261
0
{
9262
0
    ImGuiContext& g = *GImGui;
9263
0
    return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9264
0
}
9265
9266
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9267
0
{
9268
    // Majority of shortcuts will be Key + any number of Mods
9269
    // We accept _Single_ mod with ImGuiKey_None.
9270
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9271
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9272
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9273
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9274
0
    ImGuiContext& g = *GImGui;
9275
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9276
0
    ImGuiKeyRoutingData* routing_data;
9277
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9278
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9279
0
    if (key == ImGuiKey_None)
9280
0
        key = ConvertSingleModFlagToKey(mods);
9281
0
    IM_ASSERT(IsNamedKey(key));
9282
9283
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9284
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9285
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9286
0
    {
9287
0
        routing_data = &rt->Entries[idx];
9288
0
        if (routing_data->Mods == mods)
9289
0
            return routing_data;
9290
0
    }
9291
9292
    // Add to linked-list
9293
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9294
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9295
0
    routing_data = &rt->Entries[routing_data_idx];
9296
0
    routing_data->Mods = (ImU16)mods;
9297
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9298
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9299
0
    return routing_data;
9300
0
}
9301
9302
// Current score encoding (lower is highest priority):
9303
//  -   0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9304
//  -   1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9305
//  -   2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9306
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9307
//  - 254: ImGuiInputFlags_RouteGlobal
9308
//  - 255: never route
9309
// 'flags' should include an explicit routing policy
9310
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9311
0
{
9312
0
    ImGuiContext& g = *GImGui;
9313
0
    if (flags & ImGuiInputFlags_RouteFocused)
9314
0
    {
9315
        // ActiveID gets top priority
9316
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9317
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9318
0
            return 1;
9319
9320
        // Score based on distance to focused window (lower is better)
9321
        // Assuming both windows are submitting a routing request,
9322
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9323
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9324
        // Assuming only WindowA is submitting a routing request,
9325
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9326
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9327
0
        if (focus_scope_id == 0)
9328
0
            return 255;
9329
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9330
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9331
0
                return 3 + index_in_focus_path;
9332
0
        return 255;
9333
0
    }
9334
0
    else if (flags & ImGuiInputFlags_RouteActive)
9335
0
    {
9336
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9337
0
            return 1;
9338
0
        return 255;
9339
0
    }
9340
0
    else if (flags & ImGuiInputFlags_RouteGlobal)
9341
0
    {
9342
0
        if (flags & ImGuiInputFlags_RouteOverActive)
9343
0
            return 0;
9344
0
        if (flags & ImGuiInputFlags_RouteOverFocused)
9345
0
            return 2;
9346
0
        return 254;
9347
0
    }
9348
0
    IM_ASSERT(0);
9349
0
    return 0;
9350
0
}
9351
9352
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9353
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9354
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9355
0
{
9356
    // Mimic 'ignore_char_inputs' logic in InputText()
9357
0
    ImGuiContext& g = *GImGui;
9358
9359
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9360
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9361
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9362
0
    if (ignore_char_inputs)
9363
0
        return false;
9364
9365
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9366
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9367
0
    return g.KeysMayBeCharInput.TestBit(key);
9368
0
}
9369
9370
// Request a desired route for an input chord (key + mods).
9371
// Return true if the route is available this frame.
9372
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9373
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9374
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9375
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9376
277k
{
9377
277k
    ImGuiContext& g = *GImGui;
9378
277k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9379
0
        flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9380
277k
    else
9381
277k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9382
277k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9383
277k
    if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9384
277k
        IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9385
9386
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9387
277k
    key_chord = FixupKeyChord(key_chord);
9388
9389
    // [DEBUG] Debug break requested by user
9390
277k
    if (g.DebugBreakInShortcutRouting == key_chord)
9391
0
        IM_DEBUG_BREAK();
9392
9393
277k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9394
0
        if (g.NavWindow == NULL)
9395
0
            return false;
9396
9397
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9398
277k
    if (flags & ImGuiInputFlags_RouteAlways)
9399
277k
    {
9400
277k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9401
277k
        return true;
9402
277k
    }
9403
9404
    // Specific culling when there's an active item.
9405
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9406
0
    {
9407
0
        if (flags & ImGuiInputFlags_RouteActive)
9408
0
            return false;
9409
9410
        // Cull shortcuts with no modifiers when it could generate a character.
9411
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9412
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9413
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9414
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9415
0
        if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9416
0
        {
9417
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9418
0
            return false;
9419
0
        }
9420
9421
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9422
0
        if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9423
0
        {
9424
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9425
0
            if (key == ImGuiKey_None)
9426
0
                key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9427
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9428
0
                return false;
9429
0
        }
9430
0
    }
9431
9432
    // Where do we evaluate route for?
9433
0
    ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9434
0
    if (flags & ImGuiInputFlags_RouteFromRootWindow)
9435
0
        focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9436
9437
0
    const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9438
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9439
0
    if (score == 255)
9440
0
        return false;
9441
9442
    // Submit routing for NEXT frame (assuming score is sufficient)
9443
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9444
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9445
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9446
0
    if (score < routing_data->RoutingNextScore)
9447
0
    {
9448
0
        routing_data->RoutingNext = owner_id;
9449
0
        routing_data->RoutingNextScore = (ImU8)score;
9450
0
    }
9451
9452
    // Return routing state for CURRENT frame
9453
0
    if (routing_data->RoutingCurr == owner_id)
9454
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9455
0
    return routing_data->RoutingCurr == owner_id;
9456
0
}
9457
9458
// Currently unused by core (but used by tests)
9459
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9460
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9461
0
{
9462
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9463
0
    key_chord = FixupKeyChord(key_chord);
9464
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9465
0
    return routing_data->RoutingCurr == routing_id;
9466
0
}
9467
9468
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9469
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9470
bool ImGui::IsKeyDown(ImGuiKey key)
9471
2.08M
{
9472
2.08M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9473
2.08M
}
9474
9475
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9476
2.10M
{
9477
2.10M
    const ImGuiKeyData* key_data = GetKeyData(key);
9478
2.10M
    if (!key_data->Down)
9479
1.98M
        return false;
9480
125k
    if (!TestKeyOwner(key, owner_id))
9481
1
        return false;
9482
125k
    return true;
9483
125k
}
9484
9485
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9486
95.3k
{
9487
95.3k
    return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9488
95.3k
}
9489
9490
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9491
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9492
565k
{
9493
565k
    const ImGuiKeyData* key_data = GetKeyData(key);
9494
565k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9495
540k
        return false;
9496
24.5k
    const float t = key_data->DownDuration;
9497
24.5k
    if (t < 0.0f)
9498
0
        return false;
9499
24.5k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9500
24.5k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9501
3.04k
        flags |= ImGuiInputFlags_Repeat;
9502
9503
24.5k
    bool pressed = (t == 0.0f);
9504
24.5k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9505
8.69k
    {
9506
8.69k
        float repeat_delay, repeat_rate;
9507
8.69k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9508
8.69k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9509
8.69k
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9510
0
        {
9511
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9512
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9513
0
            ImGuiContext& g = *GImGui;
9514
0
            double key_pressed_time = g.Time - t + 0.00001f;
9515
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9516
0
                pressed = false;
9517
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9518
0
                pressed = false;
9519
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9520
0
                pressed = false;
9521
0
        }
9522
8.69k
    }
9523
24.5k
    if (!pressed)
9524
18.9k
        return false;
9525
5.60k
    if (!TestKeyOwner(key, owner_id))
9526
0
        return false;
9527
5.60k
    return true;
9528
5.60k
}
9529
9530
bool ImGui::IsKeyReleased(ImGuiKey key)
9531
5.91k
{
9532
5.91k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9533
5.91k
}
9534
9535
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9536
5.91k
{
9537
5.91k
    const ImGuiKeyData* key_data = GetKeyData(key);
9538
5.91k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9539
4.63k
        return false;
9540
1.28k
    if (!TestKeyOwner(key, owner_id))
9541
0
        return false;
9542
1.28k
    return true;
9543
1.28k
}
9544
9545
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9546
6
{
9547
6
    ImGuiContext& g = *GImGui;
9548
6
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9549
6
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9550
6
}
9551
9552
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9553
0
{
9554
0
    ImGuiContext& g = *GImGui;
9555
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9556
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9557
0
}
9558
9559
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9560
22
{
9561
22
    return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9562
22
}
9563
9564
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9565
80
{
9566
80
    ImGuiContext& g = *GImGui;
9567
80
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9568
80
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9569
26
        return false;
9570
54
    const float t = g.IO.MouseDownDuration[button];
9571
54
    if (t < 0.0f)
9572
0
        return false;
9573
54
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9574
9575
54
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9576
54
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9577
54
    if (!pressed)
9578
53
        return false;
9579
9580
1
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9581
0
        return false;
9582
9583
1
    return true;
9584
1
}
9585
9586
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9587
0
{
9588
0
    ImGuiContext& g = *GImGui;
9589
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9590
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9591
0
}
9592
9593
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9594
58
{
9595
58
    ImGuiContext& g = *GImGui;
9596
58
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9597
58
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9598
58
}
9599
9600
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9601
22
{
9602
22
    ImGuiContext& g = *GImGui;
9603
22
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9604
22
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9605
22
}
9606
9607
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9608
0
{
9609
0
    ImGuiContext& g = *GImGui;
9610
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9611
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9612
0
}
9613
9614
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9615
0
{
9616
0
    ImGuiContext& g = *GImGui;
9617
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9618
0
    return g.IO.MouseClickedCount[button];
9619
0
}
9620
9621
// Test if mouse cursor is hovering given rectangle
9622
// NB- Rectangle is clipped by our current clip setting
9623
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9624
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9625
659k
{
9626
659k
    ImGuiContext& g = *GImGui;
9627
9628
    // Clip
9629
659k
    ImRect rect_clipped(r_min, r_max);
9630
659k
    if (clip)
9631
358k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9632
9633
    // Hit testing, expanded for touch input
9634
659k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9635
646k
        return false;
9636
12.8k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9637
0
        return false;
9638
12.8k
    return true;
9639
12.8k
}
9640
9641
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9642
// [Internal] This doesn't test if the button is pressed
9643
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9644
148
{
9645
148
    ImGuiContext& g = *GImGui;
9646
148
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9647
148
    if (lock_threshold < 0.0f)
9648
148
        lock_threshold = g.IO.MouseDragThreshold;
9649
148
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9650
148
}
9651
9652
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9653
167
{
9654
167
    ImGuiContext& g = *GImGui;
9655
167
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9656
167
    if (!g.IO.MouseDown[button])
9657
19
        return false;
9658
148
    return IsMouseDragPastThreshold(button, lock_threshold);
9659
167
}
9660
9661
ImVec2 ImGui::GetMousePos()
9662
15.3k
{
9663
15.3k
    ImGuiContext& g = *GImGui;
9664
15.3k
    return g.IO.MousePos;
9665
15.3k
}
9666
9667
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9668
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9669
void ImGui::TeleportMousePos(const ImVec2& pos)
9670
0
{
9671
0
    ImGuiContext& g = *GImGui;
9672
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9673
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9674
0
    g.IO.WantSetMousePos = true;
9675
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9676
0
}
9677
9678
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9679
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9680
0
{
9681
0
    ImGuiContext& g = *GImGui;
9682
0
    if (g.BeginPopupStack.Size > 0)
9683
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9684
0
    return g.IO.MousePos;
9685
0
}
9686
9687
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9688
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9689
538k
{
9690
    // The assert is only to silence a false-positive in XCode Static Analysis.
9691
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9692
538k
    IM_ASSERT(GImGui != NULL);
9693
538k
    const float MOUSE_INVALID = -256000.0f;
9694
538k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9695
538k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9696
538k
}
9697
9698
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9699
bool ImGui::IsAnyMouseDown()
9700
0
{
9701
0
    ImGuiContext& g = *GImGui;
9702
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9703
0
        if (g.IO.MouseDown[n])
9704
0
            return true;
9705
0
    return false;
9706
0
}
9707
9708
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9709
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9710
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9711
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9712
0
{
9713
0
    ImGuiContext& g = *GImGui;
9714
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9715
0
    if (lock_threshold < 0.0f)
9716
0
        lock_threshold = g.IO.MouseDragThreshold;
9717
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9718
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9719
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9720
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9721
0
    return ImVec2(0.0f, 0.0f);
9722
0
}
9723
9724
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9725
0
{
9726
0
    ImGuiContext& g = *GImGui;
9727
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9728
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9729
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9730
0
}
9731
9732
// Get desired mouse cursor shape.
9733
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9734
// updated during the frame, and locked in EndFrame()/Render().
9735
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9736
ImGuiMouseCursor ImGui::GetMouseCursor()
9737
0
{
9738
0
    ImGuiContext& g = *GImGui;
9739
0
    return g.MouseCursor;
9740
0
}
9741
9742
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9743
4
{
9744
4
    ImGuiContext& g = *GImGui;
9745
4
    g.MouseCursor = cursor_type;
9746
4
}
9747
9748
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9749
971k
{
9750
971k
    IM_ASSERT(ImGui::IsAliasKey(key));
9751
971k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9752
971k
    key_data->Down = v;
9753
971k
    key_data->AnalogValue = analog_value;
9754
971k
}
9755
9756
// [Internal] Do not use directly
9757
static ImGuiKeyChord GetMergedModsFromKeys()
9758
277k
{
9759
277k
    ImGuiKeyChord mods = 0;
9760
277k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9761
277k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9762
277k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9763
277k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9764
277k
    return mods;
9765
277k
}
9766
9767
static void ImGui::UpdateKeyboardInputs()
9768
138k
{
9769
138k
    ImGuiContext& g = *GImGui;
9770
138k
    ImGuiIO& io = g.IO;
9771
9772
138k
    if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9773
0
        io.ClearInputKeys();
9774
9775
    // Import legacy keys or verify they are not used
9776
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9777
    if (io.BackendUsingLegacyKeyArrays == 0)
9778
    {
9779
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9780
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9781
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9782
    }
9783
    else
9784
    {
9785
        if (g.FrameCount == 0)
9786
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9787
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9788
9789
        // Build reverse KeyMap (Named -> Legacy)
9790
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9791
            if (io.KeyMap[n] != -1)
9792
            {
9793
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9794
                io.KeyMap[io.KeyMap[n]] = n;
9795
            }
9796
9797
        // Import legacy keys into new ones
9798
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9799
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9800
            {
9801
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9802
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9803
                io.KeysData[key].Down = io.KeysDown[n];
9804
                if (key != n)
9805
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9806
                io.BackendUsingLegacyKeyArrays = 1;
9807
            }
9808
        if (io.BackendUsingLegacyKeyArrays == 1)
9809
        {
9810
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9811
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9812
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9813
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9814
        }
9815
    }
9816
#endif
9817
9818
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9819
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9820
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9821
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9822
    {
9823
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9824
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9825
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9826
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9827
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9828
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9829
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9830
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9831
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9832
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9833
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9834
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9835
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9836
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9837
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9838
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9839
        #undef NAV_MAP_KEY
9840
    }
9841
#endif
9842
9843
    // Update aliases
9844
832k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9845
694k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9846
138k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9847
138k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9848
9849
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9850
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9851
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9852
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9853
138k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9854
138k
    io.KeyMods = GetMergedModsFromKeys();
9855
138k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9856
138k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9857
138k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9858
138k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9859
138k
    if (prev_key_mods != io.KeyMods)
9860
0
        g.LastKeyModsChangeTime = g.Time;
9861
138k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9862
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9863
9864
    // Clear gamepad data if disabled
9865
138k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9866
3.47M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9867
3.33M
        {
9868
3.33M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9869
3.33M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9870
3.33M
        }
9871
9872
    // Update keys
9873
21.5M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9874
21.3M
    {
9875
21.3M
        ImGuiKeyData* key_data = &io.KeysData[i];
9876
21.3M
        key_data->DownDurationPrev = key_data->DownDuration;
9877
21.3M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9878
21.3M
        if (key_data->DownDuration == 0.0f)
9879
20.7k
        {
9880
20.7k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9881
20.7k
            if (IsKeyboardKey(key))
9882
9.81k
                g.LastKeyboardKeyPressTime = g.Time;
9883
10.8k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9884
0
                g.LastKeyboardKeyPressTime = g.Time;
9885
20.7k
        }
9886
21.3M
    }
9887
9888
    // Update keys/input owner (named keys only): one entry per key
9889
21.5M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9890
21.3M
    {
9891
21.3M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9892
21.3M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9893
21.3M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9894
21.3M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9895
21.0M
            owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9896
21.3M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9897
21.3M
    }
9898
9899
    // Update key routing (for e.g. shortcuts)
9900
138k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9901
138k
}
9902
9903
static void ImGui::UpdateMouseInputs()
9904
138k
{
9905
138k
    ImGuiContext& g = *GImGui;
9906
138k
    ImGuiIO& io = g.IO;
9907
9908
    // Mouse Wheel swapping flag
9909
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9910
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9911
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9912
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9913
138k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9914
9915
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9916
138k
    if (IsMousePosValid(&io.MousePos))
9917
71.2k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9918
9919
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9920
138k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9921
70.8k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9922
68.0k
    else
9923
68.0k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9924
9925
    // Update stationary timer.
9926
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9927
138k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9928
138k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9929
138k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9930
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9931
9932
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9933
138k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9934
4.35k
        g.NavDisableMouseHover = false;
9935
9936
832k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9937
694k
    {
9938
694k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9939
694k
        io.MouseClickedCount[i] = 0; // Will be filled below
9940
694k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9941
694k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9942
694k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9943
694k
        if (io.MouseClicked[i])
9944
5.92k
        {
9945
5.92k
            bool is_repeated_click = false;
9946
5.92k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9947
4.86k
            {
9948
4.86k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9949
4.86k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9950
4.24k
                    is_repeated_click = true;
9951
4.86k
            }
9952
5.92k
            if (is_repeated_click)
9953
4.24k
                io.MouseClickedLastCount[i]++;
9954
1.67k
            else
9955
1.67k
                io.MouseClickedLastCount[i] = 1;
9956
5.92k
            io.MouseClickedTime[i] = g.Time;
9957
5.92k
            io.MouseClickedPos[i] = io.MousePos;
9958
5.92k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9959
5.92k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9960
5.92k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9961
5.92k
        }
9962
688k
        else if (io.MouseDown[i])
9963
159k
        {
9964
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9965
159k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9966
159k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9967
159k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9968
159k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9969
159k
        }
9970
9971
        // We provide io.MouseDoubleClicked[] as a legacy service
9972
694k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9973
9974
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9975
694k
        if (io.MouseClicked[i])
9976
5.92k
            g.NavDisableMouseHover = false;
9977
694k
    }
9978
138k
}
9979
9980
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9981
0
{
9982
0
    ImGuiContext& g = *GImGui;
9983
0
    if (window)
9984
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9985
0
    else
9986
0
        g.WheelingWindowReleaseTimer = 0.0f;
9987
0
    if (g.WheelingWindow == window)
9988
0
        return;
9989
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9990
0
    g.WheelingWindow = window;
9991
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9992
0
    if (window == NULL)
9993
0
    {
9994
0
        g.WheelingWindowStartFrame = -1;
9995
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9996
0
    }
9997
0
}
9998
9999
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10000
14
{
10001
    // For each axis, find window in the hierarchy that may want to use scrolling
10002
14
    ImGuiContext& g = *GImGui;
10003
14
    ImGuiWindow* windows[2] = { NULL, NULL };
10004
42
    for (int axis = 0; axis < 2; axis++)
10005
28
        if (wheel[axis] != 0.0f)
10006
21
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10007
0
            {
10008
                // Bubble up into parent window if:
10009
                // - a child window doesn't allow any scrolling.
10010
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10011
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10012
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10013
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10014
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10015
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10016
0
                    break; // select this window
10017
0
            }
10018
14
    if (windows[0] == NULL && windows[1] == NULL)
10019
0
        return NULL;
10020
10021
    // If there's only one window or only one axis then there's no ambiguity
10022
14
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10023
14
        return windows[1] ? windows[1] : windows[0];
10024
10025
    // If candidate are different windows we need to decide which one to prioritize
10026
    // - First frame: only find a winner if one axis is zero.
10027
    // - Subsequent frames: only find a winner when one is more than the other.
10028
0
    if (g.WheelingWindowStartFrame == -1)
10029
0
        g.WheelingWindowStartFrame = g.FrameCount;
10030
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10031
0
    {
10032
0
        g.WheelingWindowWheelRemainder = wheel;
10033
0
        return NULL;
10034
0
    }
10035
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10036
0
}
10037
10038
// Called by NewFrame()
10039
void ImGui::UpdateMouseWheel()
10040
138k
{
10041
    // Reset the locked window if we move the mouse or after the timer elapses.
10042
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10043
138k
    ImGuiContext& g = *GImGui;
10044
138k
    if (g.WheelingWindow != NULL)
10045
0
    {
10046
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10047
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10048
0
            g.WheelingWindowReleaseTimer = 0.0f;
10049
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
10050
0
            LockWheelingWindow(NULL, 0.0f);
10051
0
    }
10052
10053
138k
    ImVec2 wheel;
10054
138k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10055
138k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10056
10057
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10058
138k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10059
138k
    if (!mouse_window || mouse_window->Collapsed)
10060
138k
        return;
10061
10062
    // Zoom / Scale window
10063
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10064
622
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10065
0
    {
10066
0
        LockWheelingWindow(mouse_window, wheel.y);
10067
0
        ImGuiWindow* window = mouse_window;
10068
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10069
0
        const float scale = new_font_scale / window->FontWindowScale;
10070
0
        window->FontWindowScale = new_font_scale;
10071
0
        if (window == window->RootWindow)
10072
0
        {
10073
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10074
0
            SetWindowPos(window, window->Pos + offset, 0);
10075
0
            window->Size = ImTrunc(window->Size * scale);
10076
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
10077
0
        }
10078
0
        return;
10079
0
    }
10080
622
    if (g.IO.KeyCtrl)
10081
0
        return;
10082
10083
    // Mouse wheel scrolling
10084
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10085
622
    if (g.IO.MouseWheelRequestAxisSwap)
10086
0
        wheel = ImVec2(wheel.y, 0.0f);
10087
10088
    // Maintain a rough average of moving magnitude on both axises
10089
    // FIXME: should by based on wall clock time rather than frame-counter
10090
622
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10091
622
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10092
10093
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10094
622
    wheel += g.WheelingWindowWheelRemainder;
10095
622
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10096
622
    if (wheel.x == 0.0f && wheel.y == 0.0f)
10097
608
        return;
10098
10099
    // Mouse wheel scrolling: find target and apply
10100
    // - don't renew lock if axis doesn't apply on the window.
10101
    // - select a main axis when both axises are being moved.
10102
14
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10103
14
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10104
14
        {
10105
14
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10106
14
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10107
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10108
14
            if (do_scroll[ImGuiAxis_X])
10109
0
            {
10110
0
                LockWheelingWindow(window, wheel.x);
10111
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
10112
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
10113
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10114
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10115
0
            }
10116
14
            if (do_scroll[ImGuiAxis_Y])
10117
0
            {
10118
0
                LockWheelingWindow(window, wheel.y);
10119
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
10120
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
10121
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10122
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10123
0
            }
10124
14
        }
10125
14
}
10126
10127
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10128
0
{
10129
0
    ImGuiContext& g = *GImGui;
10130
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10131
0
}
10132
10133
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10134
0
{
10135
0
    ImGuiContext& g = *GImGui;
10136
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10137
0
}
10138
10139
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10140
static const char* GetInputSourceName(ImGuiInputSource source)
10141
0
{
10142
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10143
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
10144
0
    return input_source_names[source];
10145
0
}
10146
static const char* GetMouseSourceName(ImGuiMouseSource source)
10147
0
{
10148
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10149
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
10150
0
    return mouse_source_names[source];
10151
0
}
10152
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10153
0
{
10154
0
    ImGuiContext& g = *GImGui;
10155
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10156
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10157
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10158
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10159
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10160
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10161
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10162
0
}
10163
#endif
10164
10165
// Process input queue
10166
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10167
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10168
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10169
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10170
138k
{
10171
138k
    ImGuiContext& g = *GImGui;
10172
138k
    ImGuiIO& io = g.IO;
10173
10174
    // Only trickle chars<>key when working with InputText()
10175
    // FIXME: InputText() could parse event trail?
10176
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10177
138k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10178
10179
138k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
10180
138k
    int  mouse_button_changed = 0x00;
10181
138k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
10182
10183
138k
    int event_n = 0;
10184
184k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
10185
61.7k
    {
10186
61.7k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10187
61.7k
        if (e->Type == ImGuiInputEventType_MousePos)
10188
8.30k
        {
10189
8.30k
            if (g.IO.WantSetMousePos)
10190
0
                continue;
10191
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10192
8.30k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10193
8.30k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10194
2.50k
                break;
10195
5.79k
            io.MousePos = event_pos;
10196
5.79k
            io.MouseSource = e->MousePos.MouseSource;
10197
5.79k
            mouse_moved = true;
10198
5.79k
        }
10199
53.3k
        else if (e->Type == ImGuiInputEventType_MouseButton)
10200
16.8k
        {
10201
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10202
16.8k
            const ImGuiMouseButton button = e->MouseButton.Button;
10203
16.8k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10204
16.8k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10205
5.97k
                break;
10206
10.8k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10207
0
                break;
10208
10.8k
            io.MouseDown[button] = e->MouseButton.Down;
10209
10.8k
            io.MouseSource = e->MouseButton.MouseSource;
10210
10.8k
            mouse_button_changed |= (1 << button);
10211
10.8k
        }
10212
36.5k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
10213
7.58k
        {
10214
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
10215
7.58k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10216
3.28k
                break;
10217
4.30k
            io.MouseWheelH += e->MouseWheel.WheelX;
10218
4.30k
            io.MouseWheel += e->MouseWheel.WheelY;
10219
4.30k
            io.MouseSource = e->MouseWheel.MouseSource;
10220
4.30k
            mouse_wheeled = true;
10221
4.30k
        }
10222
29.0k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
10223
0
        {
10224
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10225
0
        }
10226
29.0k
        else if (e->Type == ImGuiInputEventType_Key)
10227
16.2k
        {
10228
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10229
16.2k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10230
0
                continue;
10231
16.2k
            ImGuiKey key = e->Key.Key;
10232
16.2k
            IM_ASSERT(key != ImGuiKey_None);
10233
16.2k
            ImGuiKeyData* key_data = GetKeyData(key);
10234
16.2k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
10235
16.2k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
10236
2.38k
                break;
10237
13.8k
            key_data->Down = e->Key.Down;
10238
13.8k
            key_data->AnalogValue = e->Key.AnalogValue;
10239
13.8k
            key_changed = true;
10240
13.8k
            key_changed_mask.SetBit(key_data_index);
10241
10242
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
10243
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10244
            io.KeysDown[key_data_index] = key_data->Down;
10245
            if (io.KeyMap[key_data_index] != -1)
10246
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
10247
#endif
10248
13.8k
        }
10249
12.7k
        else if (e->Type == ImGuiInputEventType_Text)
10250
7.27k
        {
10251
7.27k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10252
0
                continue;
10253
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10254
7.27k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10255
1.76k
                break;
10256
5.50k
            unsigned int c = e->Text.Char;
10257
5.50k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10258
5.50k
            if (trickle_interleaved_keys_and_text)
10259
0
                text_inputted = true;
10260
5.50k
        }
10261
5.45k
        else if (e->Type == ImGuiInputEventType_Focus)
10262
5.45k
        {
10263
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10264
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10265
5.45k
            const bool focus_lost = !e->AppFocused.Focused;
10266
5.45k
            io.AppFocusLost = focus_lost;
10267
5.45k
        }
10268
0
        else
10269
0
        {
10270
0
            IM_ASSERT(0 && "Unknown event!");
10271
0
        }
10272
61.7k
    }
10273
10274
    // Record trail (for domain-specific applications wanting to access a precise trail)
10275
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10276
184k
    for (int n = 0; n < event_n; n++)
10277
45.7k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10278
10279
    // [DEBUG]
10280
138k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10281
138k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10282
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10283
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10284
138k
#endif
10285
10286
    // Remaining events will be processed on the next frame
10287
138k
    if (event_n == g.InputEventsQueue.Size)
10288
122k
        g.InputEventsQueue.resize(0);
10289
15.9k
    else
10290
15.9k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10291
10292
    // Clear buttons state when focus is lost
10293
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10294
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10295
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10296
138k
    if (g.IO.AppFocusLost)
10297
5.34k
    {
10298
5.34k
        g.IO.ClearInputKeys();
10299
5.34k
        g.IO.ClearInputMouse();
10300
5.34k
    }
10301
138k
}
10302
10303
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10304
3
{
10305
3
    if (!IsNamedKeyOrMod(key))
10306
0
        return ImGuiKeyOwner_NoOwner;
10307
10308
3
    ImGuiContext& g = *GImGui;
10309
3
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10310
3
    ImGuiID owner_id = owner_data->OwnerCurr;
10311
10312
3
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10313
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10314
0
            return ImGuiKeyOwner_NoOwner;
10315
10316
3
    return owner_id;
10317
3
}
10318
10319
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10320
// TestKeyOwner(..., None) : (owner == None)
10321
// TestKeyOwner(..., Any)  : no owner test
10322
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10323
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10324
421k
{
10325
421k
    if (!IsNamedKeyOrMod(key))
10326
0
        return true;
10327
10328
421k
    ImGuiContext& g = *GImGui;
10329
421k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10330
325
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10331
1
            return false;
10332
10333
421k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10334
421k
    if (owner_id == ImGuiKeyOwner_Any)
10335
126k
        return (owner_data->LockThisFrame == false);
10336
10337
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10338
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10339
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10340
295k
    if (owner_data->OwnerCurr != owner_id)
10341
0
    {
10342
0
        if (owner_data->LockThisFrame)
10343
0
            return false;
10344
0
        if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10345
0
            return false;
10346
0
    }
10347
10348
295k
    return true;
10349
295k
}
10350
10351
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10352
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10353
// - SetKeyOwner(..., None)              : clears owner
10354
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10355
// - SetKeyOwner(..., Any or None, Lock) : set lock
10356
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10357
0
{
10358
0
    ImGuiContext& g = *GImGui;
10359
0
    IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10360
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10361
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10362
10363
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10364
0
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10365
10366
    // We cannot lock by default as it would likely break lots of legacy code.
10367
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10368
0
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10369
0
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10370
0
}
10371
10372
// Rarely used helper
10373
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10374
0
{
10375
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10376
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10377
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10378
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10379
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10380
0
}
10381
10382
// This is more or less equivalent to:
10383
//   if (IsItemHovered() || IsItemActive())
10384
//       SetKeyOwner(key, GetItemID());
10385
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10386
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10387
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10388
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10389
0
{
10390
0
    ImGuiContext& g = *GImGui;
10391
0
    ImGuiID id = g.LastItemData.ID;
10392
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10393
0
        return;
10394
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10395
0
        flags |= ImGuiInputFlags_CondDefault_;
10396
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10397
0
    {
10398
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10399
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10400
0
    }
10401
0
}
10402
10403
// This is the only public API until we expose owner_id versions of the API as replacements.
10404
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10405
0
{
10406
0
    return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10407
0
}
10408
10409
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10410
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10411
277k
{
10412
277k
    ImGuiContext& g = *GImGui;
10413
277k
    key_chord = FixupKeyChord(key_chord);
10414
277k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10415
277k
    if (g.IO.KeyMods != mods)
10416
277k
        return false;
10417
10418
    // Special storage location for mods
10419
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10420
0
    if (key == ImGuiKey_None)
10421
0
        key = ConvertSingleModFlagToKey(mods);
10422
0
    if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10423
0
        return false;
10424
0
    return true;
10425
0
}
10426
10427
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10428
0
{
10429
0
    ImGuiContext& g = *GImGui;
10430
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10431
0
    g.NextItemData.Shortcut = key_chord;
10432
0
    g.NextItemData.ShortcutFlags = flags;
10433
0
}
10434
10435
// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10436
void ImGui::ItemHandleShortcut(ImGuiID id)
10437
0
{
10438
0
    ImGuiContext& g = *GImGui;
10439
0
    ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10440
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10441
10442
0
    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
10443
0
        return;
10444
0
    if (flags & ImGuiInputFlags_Tooltip)
10445
0
    {
10446
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10447
0
        g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10448
0
    }
10449
0
    if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10450
0
        return;
10451
10452
    // FIXME: Generalize Activation queue?
10453
0
    g.NavActivateId = id; // Will effectively disable clipping.
10454
0
    g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10455
    //if (g.ActiveId == 0 || g.ActiveId == id)
10456
0
    g.NavActivateDownId = g.NavActivatePressedId = id;
10457
0
    NavHighlightActivated(id);
10458
0
}
10459
10460
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10461
0
{
10462
0
    return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10463
0
}
10464
10465
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10466
277k
{
10467
277k
    ImGuiContext& g = *GImGui;
10468
    //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10469
10470
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10471
277k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10472
0
        flags |= ImGuiInputFlags_RouteFocused;
10473
10474
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10475
    // Effectively makes Shortcut() always input-owner aware.
10476
277k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10477
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10478
10479
277k
    if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10480
0
        return false;
10481
10482
    // Submit route
10483
277k
    if (!SetShortcutRouting(key_chord, flags, owner_id))
10484
0
        return false;
10485
10486
    // Default repeat behavior for Shortcut()
10487
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10488
277k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10489
277k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10490
10491
277k
    if (!IsKeyChordPressed(key_chord, flags, owner_id))
10492
277k
        return false;
10493
10494
    // Claim mods during the press
10495
0
    SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10496
10497
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10498
0
    return true;
10499
277k
}
10500
10501
10502
//-----------------------------------------------------------------------------
10503
// [SECTION] ERROR CHECKING
10504
//-----------------------------------------------------------------------------
10505
10506
// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10507
// Called by IMGUI_CHECKVERSION().
10508
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10509
// If this triggers you have mismatched headers and compiled code versions.
10510
// - It could be because of a build issue (using new headers with old compiled code)
10511
// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10512
//   THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10513
//   Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10514
//   Otherwise it is possible that different compilation units would see different structure layout.
10515
//   If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10516
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10517
1
{
10518
1
    bool error = false;
10519
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10520
1
    if (sz_io    != sizeof(ImGuiIO))    { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10521
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10522
1
    if (sz_vec2  != sizeof(ImVec2))     { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10523
1
    if (sz_vec4  != sizeof(ImVec4))     { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10524
1
    if (sz_vert  != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10525
1
    if (sz_idx   != sizeof(ImDrawIdx))  { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10526
1
    return !error;
10527
1
}
10528
10529
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10530
// This is causing issues and ambiguity and we need to retire that.
10531
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10532
// [Scenario 1]
10533
//  Previously this would make the window content size ~200x200:
10534
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10535
//  Instead, please submit an item:
10536
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10537
//  Alternative:
10538
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10539
// [Scenario 2]
10540
//  For reference this is one of the issue what we aim to fix with this change:
10541
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10542
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10543
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10544
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10545
0
{
10546
0
    ImGuiContext& g = *GImGui;
10547
0
    ImGuiWindow* window = g.CurrentWindow;
10548
0
    IM_ASSERT(window->DC.IsSetPos);
10549
0
    window->DC.IsSetPos = false;
10550
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10551
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10552
0
        return;
10553
0
    if (window->SkipItems)
10554
0
        return;
10555
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10556
#else
10557
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10558
#endif
10559
0
}
10560
10561
static void ImGui::ErrorCheckNewFrameSanityChecks()
10562
138k
{
10563
138k
    ImGuiContext& g = *GImGui;
10564
10565
    // Check user IM_ASSERT macro
10566
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10567
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10568
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10569
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10570
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10571
138k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10572
10573
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10574
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10575
#ifdef __EMSCRIPTEN__
10576
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10577
        g.IO.DeltaTime = 0.00001f;
10578
#endif
10579
10580
    // Check user data
10581
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10582
138k
    IM_ASSERT(g.Initialized);
10583
138k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10584
138k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10585
138k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10586
138k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10587
138k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10588
138k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10589
138k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10590
138k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10591
138k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10592
138k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10593
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10594
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10595
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10596
10597
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10598
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10599
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10600
#endif
10601
10602
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10603
138k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10604
138k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10605
138k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10606
138k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10607
10608
    // Perform simple checks: multi-viewport and platform windows support
10609
138k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10610
1
    {
10611
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10612
0
        {
10613
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10614
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10615
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10616
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10617
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10618
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10619
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10620
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10621
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10622
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10623
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10624
0
        }
10625
1
        else
10626
1
        {
10627
            // Disable feature, our backends do not support it
10628
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10629
1
        }
10630
10631
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10632
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10633
0
        {
10634
0
            IM_UNUSED(mon);
10635
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10636
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10637
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10638
0
        }
10639
1
    }
10640
138k
}
10641
10642
static void ImGui::ErrorCheckEndFrameSanityChecks()
10643
138k
{
10644
138k
    ImGuiContext& g = *GImGui;
10645
10646
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10647
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10648
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10649
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10650
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10651
    // while still correctly asserting on mid-frame key press events.
10652
138k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10653
138k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10654
138k
    IM_UNUSED(key_mods);
10655
10656
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10657
    //ErrorCheckEndFrameRecover();
10658
10659
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10660
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10661
138k
    if (g.CurrentWindowStack.Size != 1)
10662
0
    {
10663
0
        if (g.CurrentWindowStack.Size > 1)
10664
0
        {
10665
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10666
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10667
0
            IM_UNUSED(window);
10668
0
            while (g.CurrentWindowStack.Size > 1)
10669
0
                End();
10670
0
        }
10671
0
        else
10672
0
        {
10673
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10674
0
        }
10675
0
    }
10676
10677
138k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10678
138k
}
10679
10680
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10681
// Must be called during or before EndFrame().
10682
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10683
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10684
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10685
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10686
0
{
10687
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10688
0
    ImGuiContext& g = *GImGui;
10689
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10690
0
    {
10691
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10692
0
        ImGuiWindow* window = g.CurrentWindow;
10693
0
        if (g.CurrentWindowStack.Size == 1)
10694
0
        {
10695
0
            IM_ASSERT(window->IsFallbackWindow);
10696
0
            break;
10697
0
        }
10698
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10699
0
        {
10700
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10701
0
            EndChild();
10702
0
        }
10703
0
        else
10704
0
        {
10705
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10706
0
            End();
10707
0
        }
10708
0
    }
10709
0
}
10710
10711
// Must be called before End()/EndChild()
10712
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10713
0
{
10714
0
    ImGuiContext& g = *GImGui;
10715
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10716
0
    {
10717
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10718
0
        EndTable();
10719
0
    }
10720
10721
0
    ImGuiWindow* window = g.CurrentWindow;
10722
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10723
0
    IM_ASSERT(window != NULL);
10724
0
    while (g.CurrentTabBar != NULL) //-V1044
10725
0
    {
10726
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10727
0
        EndTabBar();
10728
0
    }
10729
0
    while (window->DC.TreeDepth > 0)
10730
0
    {
10731
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10732
0
        TreePop();
10733
0
    }
10734
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10735
0
    {
10736
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10737
0
        EndGroup();
10738
0
    }
10739
0
    while (window->IDStack.Size > 1)
10740
0
    {
10741
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10742
0
        PopID();
10743
0
    }
10744
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10745
0
    {
10746
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10747
0
        if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10748
0
            EndDisabled();
10749
0
        else
10750
0
        {
10751
0
            EndDisabledOverrideReenable();
10752
0
            g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10753
0
        }
10754
0
    }
10755
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10756
0
    {
10757
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10758
0
        PopStyleColor();
10759
0
    }
10760
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10761
0
    {
10762
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10763
0
        PopItemFlag();
10764
0
    }
10765
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10766
0
    {
10767
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10768
0
        PopStyleVar();
10769
0
    }
10770
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10771
0
    {
10772
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10773
0
        PopFont();
10774
0
    }
10775
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10776
0
    {
10777
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10778
0
        PopFocusScope();
10779
0
    }
10780
0
}
10781
10782
// Save current stack sizes for later compare
10783
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10784
300k
{
10785
300k
    ImGuiContext& g = *ctx;
10786
300k
    ImGuiWindow* window = g.CurrentWindow;
10787
300k
    SizeOfIDStack = (short)window->IDStack.Size;
10788
300k
    SizeOfColorStack = (short)g.ColorStack.Size;
10789
300k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10790
300k
    SizeOfFontStack = (short)g.FontStack.Size;
10791
300k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10792
300k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10793
300k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10794
300k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10795
300k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10796
300k
}
10797
10798
// Compare to detect usage errors
10799
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10800
300k
{
10801
300k
    ImGuiContext& g = *ctx;
10802
300k
    ImGuiWindow* window = g.CurrentWindow;
10803
300k
    IM_UNUSED(window);
10804
10805
    // Window stacks
10806
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10807
300k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10808
10809
    // Global stacks
10810
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10811
300k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10812
300k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10813
300k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10814
300k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10815
300k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10816
300k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10817
300k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10818
300k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10819
300k
}
10820
10821
//-----------------------------------------------------------------------------
10822
// [SECTION] ITEM SUBMISSION
10823
//-----------------------------------------------------------------------------
10824
// - KeepAliveID()
10825
// - ItemAdd()
10826
//-----------------------------------------------------------------------------
10827
10828
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10829
void ImGui::KeepAliveID(ImGuiID id)
10830
451k
{
10831
451k
    ImGuiContext& g = *GImGui;
10832
451k
    if (g.ActiveId == id)
10833
290
        g.ActiveIdIsAlive = id;
10834
451k
    if (g.ActiveIdPreviousFrame == id)
10835
291
        g.ActiveIdPreviousFrameIsAlive = true;
10836
451k
}
10837
10838
// Declare item bounding box for clipping and interaction.
10839
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10840
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10841
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10842
IM_MSVC_RUNTIME_CHECKS_OFF
10843
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10844
453k
{
10845
453k
    ImGuiContext& g = *GImGui;
10846
453k
    ImGuiWindow* window = g.CurrentWindow;
10847
10848
    // Set item data
10849
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10850
453k
    g.LastItemData.ID = id;
10851
453k
    g.LastItemData.Rect = bb;
10852
453k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10853
453k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10854
453k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10855
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10856
10857
453k
    if (id != 0)
10858
450k
    {
10859
450k
        KeepAliveID(id);
10860
10861
        // Directional navigation processing
10862
        // Runs prior to clipping early-out
10863
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10864
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10865
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10866
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10867
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10868
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10869
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10870
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10871
450k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10872
296k
        {
10873
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10874
296k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10875
296k
            if (g.NavId == id || g.NavAnyRequest)
10876
4.81k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10877
558
                    if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10878
558
                        NavProcessItem();
10879
296k
        }
10880
10881
450k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10882
0
            ItemHandleShortcut(id);
10883
450k
    }
10884
10885
    // Lightweight clear of SetNextItemXXX data.
10886
453k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10887
453k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10888
10889
#ifdef IMGUI_ENABLE_TEST_ENGINE
10890
    if (id != 0)
10891
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10892
#endif
10893
10894
    // Clipping test
10895
    // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10896
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10897
453k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10898
453k
    if (!is_rect_visible)
10899
101k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10900
101k
            if (!g.ItemUnclipByLog)
10901
101k
                return false;
10902
10903
    // [DEBUG]
10904
352k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10905
352k
    if (id != 0)
10906
352k
    {
10907
352k
        if (id == g.DebugLocateId)
10908
0
            DebugLocateItemResolveWithLastItem();
10909
10910
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10911
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10912
        // READ THE FAQ: https://dearimgui.com/faq
10913
352k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10914
352k
    }
10915
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10916
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10917
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10918
352k
#endif
10919
10920
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10921
352k
    if (is_rect_visible)
10922
352k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10923
352k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10924
5.05k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10925
352k
    return true;
10926
453k
}
10927
IM_MSVC_RUNTIME_CHECKS_RESTORE
10928
10929
//-----------------------------------------------------------------------------
10930
// [SECTION] LAYOUT
10931
//-----------------------------------------------------------------------------
10932
// - ItemSize()
10933
// - SameLine()
10934
// - GetCursorScreenPos()
10935
// - SetCursorScreenPos()
10936
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10937
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10938
// - GetCursorStartPos()
10939
// - Indent()
10940
// - Unindent()
10941
// - SetNextItemWidth()
10942
// - PushItemWidth()
10943
// - PushMultiItemsWidths()
10944
// - PopItemWidth()
10945
// - CalcItemWidth()
10946
// - CalcItemSize()
10947
// - GetTextLineHeight()
10948
// - GetTextLineHeightWithSpacing()
10949
// - GetFrameHeight()
10950
// - GetFrameHeightWithSpacing()
10951
// - GetContentRegionMax()
10952
// - GetContentRegionMaxAbs() [Internal]
10953
// - GetContentRegionAvail(),
10954
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10955
// - BeginGroup()
10956
// - EndGroup()
10957
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10958
//-----------------------------------------------------------------------------
10959
10960
// Advance cursor given item size for layout.
10961
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10962
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10963
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10964
IM_MSVC_RUNTIME_CHECKS_OFF
10965
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10966
26.0k
{
10967
26.0k
    ImGuiContext& g = *GImGui;
10968
26.0k
    ImGuiWindow* window = g.CurrentWindow;
10969
26.0k
    if (window->SkipItems)
10970
0
        return;
10971
10972
    // We increase the height in this function to accommodate for baseline offset.
10973
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10974
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10975
26.0k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10976
10977
26.0k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10978
26.0k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10979
10980
    // Always align ourselves on pixel boundaries
10981
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10982
26.0k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10983
26.0k
    window->DC.CursorPosPrevLine.y = line_y1;
10984
26.0k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10985
26.0k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10986
26.0k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10987
26.0k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10988
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10989
10990
26.0k
    window->DC.PrevLineSize.y = line_height;
10991
26.0k
    window->DC.CurrLineSize.y = 0.0f;
10992
26.0k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10993
26.0k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10994
26.0k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10995
10996
    // Horizontal layout mode
10997
26.0k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10998
0
        SameLine();
10999
26.0k
}
11000
IM_MSVC_RUNTIME_CHECKS_RESTORE
11001
11002
// Gets back to previous line and continue with horizontal layout
11003
//      offset_from_start_x == 0 : follow right after previous item
11004
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11005
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11006
//      spacing_w >= 0           : enforce spacing amount
11007
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11008
0
{
11009
0
    ImGuiContext& g = *GImGui;
11010
0
    ImGuiWindow* window = g.CurrentWindow;
11011
0
    if (window->SkipItems)
11012
0
        return;
11013
11014
0
    if (offset_from_start_x != 0.0f)
11015
0
    {
11016
0
        if (spacing_w < 0.0f)
11017
0
            spacing_w = 0.0f;
11018
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11019
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11020
0
    }
11021
0
    else
11022
0
    {
11023
0
        if (spacing_w < 0.0f)
11024
0
            spacing_w = g.Style.ItemSpacing.x;
11025
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11026
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11027
0
    }
11028
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
11029
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11030
0
    window->DC.IsSameLine = true;
11031
0
}
11032
11033
ImVec2 ImGui::GetCursorScreenPos()
11034
38.2k
{
11035
38.2k
    ImGuiWindow* window = GetCurrentWindowRead();
11036
38.2k
    return window->DC.CursorPos;
11037
38.2k
}
11038
11039
void ImGui::SetCursorScreenPos(const ImVec2& pos)
11040
0
{
11041
0
    ImGuiWindow* window = GetCurrentWindow();
11042
0
    window->DC.CursorPos = pos;
11043
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11044
0
    window->DC.IsSetPos = true;
11045
0
}
11046
11047
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11048
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11049
ImVec2 ImGui::GetCursorPos()
11050
0
{
11051
0
    ImGuiWindow* window = GetCurrentWindowRead();
11052
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
11053
0
}
11054
11055
float ImGui::GetCursorPosX()
11056
0
{
11057
0
    ImGuiWindow* window = GetCurrentWindowRead();
11058
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11059
0
}
11060
11061
float ImGui::GetCursorPosY()
11062
0
{
11063
0
    ImGuiWindow* window = GetCurrentWindowRead();
11064
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11065
0
}
11066
11067
void ImGui::SetCursorPos(const ImVec2& local_pos)
11068
0
{
11069
0
    ImGuiWindow* window = GetCurrentWindow();
11070
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11071
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11072
0
    window->DC.IsSetPos = true;
11073
0
}
11074
11075
void ImGui::SetCursorPosX(float x)
11076
0
{
11077
0
    ImGuiWindow* window = GetCurrentWindow();
11078
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11079
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11080
0
    window->DC.IsSetPos = true;
11081
0
}
11082
11083
void ImGui::SetCursorPosY(float y)
11084
0
{
11085
0
    ImGuiWindow* window = GetCurrentWindow();
11086
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11087
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11088
0
    window->DC.IsSetPos = true;
11089
0
}
11090
11091
ImVec2 ImGui::GetCursorStartPos()
11092
0
{
11093
0
    ImGuiWindow* window = GetCurrentWindowRead();
11094
0
    return window->DC.CursorStartPos - window->Pos;
11095
0
}
11096
11097
void ImGui::Indent(float indent_w)
11098
0
{
11099
0
    ImGuiContext& g = *GImGui;
11100
0
    ImGuiWindow* window = GetCurrentWindow();
11101
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11102
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11103
0
}
11104
11105
void ImGui::Unindent(float indent_w)
11106
0
{
11107
0
    ImGuiContext& g = *GImGui;
11108
0
    ImGuiWindow* window = GetCurrentWindow();
11109
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11110
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11111
0
}
11112
11113
// Affect large frame+labels widgets only.
11114
void ImGui::SetNextItemWidth(float item_width)
11115
0
{
11116
0
    ImGuiContext& g = *GImGui;
11117
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
11118
0
    g.NextItemData.Width = item_width;
11119
0
}
11120
11121
// FIXME: Remove the == 0.0f behavior?
11122
void ImGui::PushItemWidth(float item_width)
11123
0
{
11124
0
    ImGuiContext& g = *GImGui;
11125
0
    ImGuiWindow* window = g.CurrentWindow;
11126
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11127
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11128
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11129
0
}
11130
11131
void ImGui::PushMultiItemsWidths(int components, float w_full)
11132
0
{
11133
0
    ImGuiContext& g = *GImGui;
11134
0
    ImGuiWindow* window = g.CurrentWindow;
11135
0
    IM_ASSERT(components > 0);
11136
0
    const ImGuiStyle& style = g.Style;
11137
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11138
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11139
0
    float prev_split = w_items;
11140
0
    for (int i = components - 1; i > 0; i--)
11141
0
    {
11142
0
        float next_split = IM_TRUNC(w_items * i / components);
11143
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11144
0
        prev_split = next_split;
11145
0
    }
11146
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11147
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11148
0
}
11149
11150
void ImGui::PopItemWidth()
11151
0
{
11152
0
    ImGuiWindow* window = GetCurrentWindow();
11153
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11154
0
    window->DC.ItemWidthStack.pop_back();
11155
0
}
11156
11157
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11158
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11159
float ImGui::CalcItemWidth()
11160
0
{
11161
0
    ImGuiContext& g = *GImGui;
11162
0
    ImGuiWindow* window = g.CurrentWindow;
11163
0
    float w;
11164
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
11165
0
        w = g.NextItemData.Width;
11166
0
    else
11167
0
        w = window->DC.ItemWidth;
11168
0
    if (w < 0.0f)
11169
0
    {
11170
0
        float region_max_x = GetContentRegionMaxAbs().x;
11171
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
11172
0
    }
11173
0
    w = IM_TRUNC(w);
11174
0
    return w;
11175
0
}
11176
11177
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11178
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11179
// Note that only CalcItemWidth() is publicly exposed.
11180
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11181
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11182
22.9k
{
11183
22.9k
    ImGuiContext& g = *GImGui;
11184
22.9k
    ImGuiWindow* window = g.CurrentWindow;
11185
11186
22.9k
    ImVec2 region_max;
11187
22.9k
    if (size.x < 0.0f || size.y < 0.0f)
11188
0
        region_max = GetContentRegionMaxAbs();
11189
11190
22.9k
    if (size.x == 0.0f)
11191
5.24k
        size.x = default_w;
11192
17.7k
    else if (size.x < 0.0f)
11193
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
11194
11195
22.9k
    if (size.y == 0.0f)
11196
2.61k
        size.y = default_h;
11197
20.3k
    else if (size.y < 0.0f)
11198
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
11199
11200
22.9k
    return size;
11201
22.9k
}
11202
11203
float ImGui::GetTextLineHeight()
11204
0
{
11205
0
    ImGuiContext& g = *GImGui;
11206
0
    return g.FontSize;
11207
0
}
11208
11209
float ImGui::GetTextLineHeightWithSpacing()
11210
22.9k
{
11211
22.9k
    ImGuiContext& g = *GImGui;
11212
22.9k
    return g.FontSize + g.Style.ItemSpacing.y;
11213
22.9k
}
11214
11215
float ImGui::GetFrameHeight()
11216
146
{
11217
146
    ImGuiContext& g = *GImGui;
11218
146
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
11219
146
}
11220
11221
float ImGui::GetFrameHeightWithSpacing()
11222
0
{
11223
0
    ImGuiContext& g = *GImGui;
11224
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11225
0
}
11226
11227
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
11228
11229
// FIXME: This is in window space (not screen space!).
11230
ImVec2 ImGui::GetContentRegionMax()
11231
0
{
11232
0
    ImGuiContext& g = *GImGui;
11233
0
    ImGuiWindow* window = g.CurrentWindow;
11234
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11235
0
    return mx - window->Pos;
11236
0
}
11237
11238
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
11239
ImVec2 ImGui::GetContentRegionMaxAbs()
11240
22.9k
{
11241
22.9k
    ImGuiContext& g = *GImGui;
11242
22.9k
    ImGuiWindow* window = g.CurrentWindow;
11243
22.9k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11244
22.9k
    return mx;
11245
22.9k
}
11246
11247
ImVec2 ImGui::GetContentRegionAvail()
11248
22.9k
{
11249
22.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
11250
22.9k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
11251
22.9k
}
11252
11253
// In window space (not screen space!)
11254
ImVec2 ImGui::GetWindowContentRegionMin()
11255
0
{
11256
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11257
0
    return window->ContentRegionRect.Min - window->Pos;
11258
0
}
11259
11260
ImVec2 ImGui::GetWindowContentRegionMax()
11261
22.9k
{
11262
22.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
11263
22.9k
    return window->ContentRegionRect.Max - window->Pos;
11264
22.9k
}
11265
11266
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11267
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11268
// FIXME-OPT: Could we safely early out on ->SkipItems?
11269
void ImGui::BeginGroup()
11270
0
{
11271
0
    ImGuiContext& g = *GImGui;
11272
0
    ImGuiWindow* window = g.CurrentWindow;
11273
11274
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
11275
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11276
0
    group_data.WindowID = window->ID;
11277
0
    group_data.BackupCursorPos = window->DC.CursorPos;
11278
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11279
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11280
0
    group_data.BackupIndent = window->DC.Indent;
11281
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
11282
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11283
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11284
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11285
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11286
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
11287
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11288
0
    group_data.EmitItem = true;
11289
11290
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11291
0
    window->DC.Indent = window->DC.GroupOffset;
11292
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11293
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11294
0
    if (g.LogEnabled)
11295
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11296
0
}
11297
11298
void ImGui::EndGroup()
11299
0
{
11300
0
    ImGuiContext& g = *GImGui;
11301
0
    ImGuiWindow* window = g.CurrentWindow;
11302
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11303
11304
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11305
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11306
11307
0
    if (window->DC.IsSetPos)
11308
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11309
11310
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
11311
11312
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11313
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11314
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
11315
0
    window->DC.Indent = group_data.BackupIndent;
11316
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11317
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11318
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11319
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11320
0
    if (g.LogEnabled)
11321
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11322
11323
0
    if (!group_data.EmitItem)
11324
0
    {
11325
0
        g.GroupStack.pop_back();
11326
0
        return;
11327
0
    }
11328
11329
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11330
0
    ItemSize(group_bb.GetSize());
11331
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11332
11333
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11334
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11335
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11336
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11337
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11338
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11339
0
    if (group_contains_curr_active_id)
11340
0
        g.LastItemData.ID = g.ActiveId;
11341
0
    else if (group_contains_prev_active_id)
11342
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11343
0
    g.LastItemData.Rect = group_bb;
11344
11345
    // Forward Hovered flag
11346
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11347
0
    if (group_contains_curr_hovered_id)
11348
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11349
11350
    // Forward Edited flag
11351
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11352
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11353
11354
    // Forward Deactivated flag
11355
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11356
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11357
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11358
11359
0
    g.GroupStack.pop_back();
11360
0
    if (g.DebugShowGroupRects)
11361
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11362
0
}
11363
11364
11365
//-----------------------------------------------------------------------------
11366
// [SECTION] SCROLLING
11367
//-----------------------------------------------------------------------------
11368
11369
// Helper to snap on edges when aiming at an item very close to the edge,
11370
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11371
// When we refactor the scrolling API this may be configurable with a flag?
11372
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11373
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11374
0
{
11375
0
    if (target <= snap_min + snap_threshold)
11376
0
        return ImLerp(snap_min, target, center_ratio);
11377
0
    if (target >= snap_max - snap_threshold)
11378
0
        return ImLerp(target, snap_max, center_ratio);
11379
0
    return target;
11380
0
}
11381
11382
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11383
300k
{
11384
300k
    ImVec2 scroll = window->Scroll;
11385
300k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11386
901k
    for (int axis = 0; axis < 2; axis++)
11387
601k
    {
11388
601k
        if (window->ScrollTarget[axis] < FLT_MAX)
11389
7.83k
        {
11390
7.83k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11391
7.83k
            float scroll_target = window->ScrollTarget[axis];
11392
7.83k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11393
0
            {
11394
0
                float snap_min = 0.0f;
11395
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11396
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11397
0
            }
11398
7.83k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11399
7.83k
        }
11400
601k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11401
601k
        if (!window->Collapsed && !window->SkipItems)
11402
329k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11403
601k
    }
11404
300k
    return scroll;
11405
300k
}
11406
11407
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11408
0
{
11409
0
    ImGuiContext& g = *GImGui;
11410
0
    ImGuiWindow* window = g.CurrentWindow;
11411
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11412
0
}
11413
11414
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11415
0
{
11416
0
    ScrollToRectEx(window, item_rect, flags);
11417
0
}
11418
11419
// Scroll to keep newly navigated item fully into view
11420
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11421
17
{
11422
17
    ImGuiContext& g = *GImGui;
11423
17
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11424
17
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11425
17
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11426
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11427
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11428
11429
    // Check that only one behavior is selected per axis
11430
17
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11431
17
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11432
11433
    // Defaults
11434
17
    ImGuiScrollFlags in_flags = flags;
11435
17
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11436
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11437
17
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11438
17
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11439
11440
17
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11441
17
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11442
17
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11443
17
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11444
11445
17
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11446
0
    {
11447
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11448
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11449
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11450
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11451
0
    }
11452
17
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11453
0
    {
11454
0
        if (can_be_fully_visible_x)
11455
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11456
0
        else
11457
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11458
0
    }
11459
11460
17
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11461
0
    {
11462
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11463
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11464
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11465
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11466
0
    }
11467
17
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11468
0
    {
11469
0
        if (can_be_fully_visible_y)
11470
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11471
0
        else
11472
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11473
0
    }
11474
11475
17
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11476
17
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11477
11478
    // Also scroll parent window to keep us into view if necessary
11479
17
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11480
0
    {
11481
        // FIXME-SCROLL: May be an option?
11482
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11483
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11484
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11485
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11486
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11487
0
    }
11488
11489
17
    return delta_scroll;
11490
17
}
11491
11492
float ImGui::GetScrollX()
11493
26.9k
{
11494
26.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
11495
26.9k
    return window->Scroll.x;
11496
26.9k
}
11497
11498
float ImGui::GetScrollY()
11499
26.9k
{
11500
26.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
11501
26.9k
    return window->Scroll.y;
11502
26.9k
}
11503
11504
float ImGui::GetScrollMaxX()
11505
0
{
11506
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11507
0
    return window->ScrollMax.x;
11508
0
}
11509
11510
float ImGui::GetScrollMaxY()
11511
0
{
11512
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11513
0
    return window->ScrollMax.y;
11514
0
}
11515
11516
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11517
4.15k
{
11518
4.15k
    window->ScrollTarget.x = scroll_x;
11519
4.15k
    window->ScrollTargetCenterRatio.x = 0.0f;
11520
4.15k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11521
4.15k
}
11522
11523
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11524
3.91k
{
11525
3.91k
    window->ScrollTarget.y = scroll_y;
11526
3.91k
    window->ScrollTargetCenterRatio.y = 0.0f;
11527
3.91k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11528
3.91k
}
11529
11530
void ImGui::SetScrollX(float scroll_x)
11531
4.01k
{
11532
4.01k
    ImGuiContext& g = *GImGui;
11533
4.01k
    SetScrollX(g.CurrentWindow, scroll_x);
11534
4.01k
}
11535
11536
void ImGui::SetScrollY(float scroll_y)
11537
3.37k
{
11538
3.37k
    ImGuiContext& g = *GImGui;
11539
3.37k
    SetScrollY(g.CurrentWindow, scroll_y);
11540
3.37k
}
11541
11542
// Note that a local position will vary depending on initial scroll value,
11543
// This is a little bit confusing so bear with us:
11544
//  - local_pos = (absolution_pos - window->Pos)
11545
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11546
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11547
//  - They mostly exist because of legacy API.
11548
// Following the rules above, when trying to work with scrolling code, consider that:
11549
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11550
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11551
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11552
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11553
0
{
11554
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11555
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11556
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11557
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11558
0
}
11559
11560
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11561
0
{
11562
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11563
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11564
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11565
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11566
0
}
11567
11568
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11569
0
{
11570
0
    ImGuiContext& g = *GImGui;
11571
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11572
0
}
11573
11574
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11575
0
{
11576
0
    ImGuiContext& g = *GImGui;
11577
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11578
0
}
11579
11580
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11581
void ImGui::SetScrollHereX(float center_x_ratio)
11582
0
{
11583
0
    ImGuiContext& g = *GImGui;
11584
0
    ImGuiWindow* window = g.CurrentWindow;
11585
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11586
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11587
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11588
11589
    // Tweak: snap on edges when aiming at an item very close to the edge
11590
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11591
0
}
11592
11593
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11594
void ImGui::SetScrollHereY(float center_y_ratio)
11595
0
{
11596
0
    ImGuiContext& g = *GImGui;
11597
0
    ImGuiWindow* window = g.CurrentWindow;
11598
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11599
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11600
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11601
11602
    // Tweak: snap on edges when aiming at an item very close to the edge
11603
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11604
0
}
11605
11606
//-----------------------------------------------------------------------------
11607
// [SECTION] TOOLTIPS
11608
//-----------------------------------------------------------------------------
11609
11610
bool ImGui::BeginTooltip()
11611
0
{
11612
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11613
0
}
11614
11615
bool ImGui::BeginItemTooltip()
11616
0
{
11617
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11618
0
        return false;
11619
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11620
0
}
11621
11622
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11623
0
{
11624
0
    ImGuiContext& g = *GImGui;
11625
11626
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11627
0
    {
11628
        // Drag and Drop tooltips are positioning differently than other tooltips:
11629
        // - offset visibility to increase visibility around mouse.
11630
        // - never clamp within outer viewport boundary.
11631
        // We call SetNextWindowPos() to enforce position and disable clamping.
11632
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11633
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11634
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11635
0
        SetNextWindowPos(tooltip_pos);
11636
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11637
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11638
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11639
0
    }
11640
11641
0
    char window_name[16];
11642
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11643
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11644
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11645
0
            if (window->Active)
11646
0
            {
11647
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11648
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11649
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11650
0
            }
11651
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11652
0
    Begin(window_name, NULL, flags | extra_window_flags);
11653
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11654
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11655
    //if (!ret)
11656
    //    End();
11657
    //return ret;
11658
0
    return true;
11659
0
}
11660
11661
void ImGui::EndTooltip()
11662
0
{
11663
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11664
0
    End();
11665
0
}
11666
11667
void ImGui::SetTooltip(const char* fmt, ...)
11668
0
{
11669
0
    va_list args;
11670
0
    va_start(args, fmt);
11671
0
    SetTooltipV(fmt, args);
11672
0
    va_end(args);
11673
0
}
11674
11675
void ImGui::SetTooltipV(const char* fmt, va_list args)
11676
0
{
11677
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11678
0
        return;
11679
0
    TextV(fmt, args);
11680
0
    EndTooltip();
11681
0
}
11682
11683
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11684
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11685
void ImGui::SetItemTooltip(const char* fmt, ...)
11686
0
{
11687
0
    va_list args;
11688
0
    va_start(args, fmt);
11689
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11690
0
        SetTooltipV(fmt, args);
11691
0
    va_end(args);
11692
0
}
11693
11694
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11695
0
{
11696
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11697
0
        SetTooltipV(fmt, args);
11698
0
}
11699
11700
11701
//-----------------------------------------------------------------------------
11702
// [SECTION] POPUPS
11703
//-----------------------------------------------------------------------------
11704
11705
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11706
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11707
0
{
11708
0
    ImGuiContext& g = *GImGui;
11709
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11710
0
    {
11711
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11712
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11713
0
        IM_ASSERT(id == 0);
11714
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11715
0
            return g.OpenPopupStack.Size > 0;
11716
0
        else
11717
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11718
0
    }
11719
0
    else
11720
0
    {
11721
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11722
0
        {
11723
            // Return true if the popup is open anywhere in the popup stack
11724
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11725
0
                if (popup_data.PopupId == id)
11726
0
                    return true;
11727
0
            return false;
11728
0
        }
11729
0
        else
11730
0
        {
11731
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11732
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11733
0
        }
11734
0
    }
11735
0
}
11736
11737
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11738
0
{
11739
0
    ImGuiContext& g = *GImGui;
11740
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11741
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11742
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11743
0
    return IsPopupOpen(id, popup_flags);
11744
0
}
11745
11746
// Also see FindBlockingModal(NULL)
11747
ImGuiWindow* ImGui::GetTopMostPopupModal()
11748
416k
{
11749
416k
    ImGuiContext& g = *GImGui;
11750
416k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11751
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11752
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11753
0
                return popup;
11754
416k
    return NULL;
11755
416k
}
11756
11757
// See Demo->Stacked Modal to confirm what this is for.
11758
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11759
138k
{
11760
138k
    ImGuiContext& g = *GImGui;
11761
138k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11762
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11763
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11764
0
                return popup;
11765
138k
    return NULL;
11766
138k
}
11767
11768
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11769
0
{
11770
0
    ImGuiContext& g = *GImGui;
11771
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11772
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11773
0
    OpenPopupEx(id, popup_flags);
11774
0
}
11775
11776
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11777
0
{
11778
0
    OpenPopupEx(id, popup_flags);
11779
0
}
11780
11781
// Mark popup as open (toggle toward open state).
11782
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11783
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11784
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11785
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11786
0
{
11787
0
    ImGuiContext& g = *GImGui;
11788
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11789
0
    const int current_stack_size = g.BeginPopupStack.Size;
11790
11791
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11792
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11793
0
            return;
11794
11795
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11796
0
    popup_ref.PopupId = id;
11797
0
    popup_ref.Window = NULL;
11798
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11799
0
    popup_ref.OpenFrameCount = g.FrameCount;
11800
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11801
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11802
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11803
11804
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11805
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11806
0
    {
11807
0
        g.OpenPopupStack.push_back(popup_ref);
11808
0
    }
11809
0
    else
11810
0
    {
11811
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11812
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11813
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11814
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11815
0
        bool keep_existing = false;
11816
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11817
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11818
0
                keep_existing = true;
11819
0
        if (keep_existing)
11820
0
        {
11821
            // No reopen
11822
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11823
0
        }
11824
0
        else
11825
0
        {
11826
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11827
0
            ClosePopupToLevel(current_stack_size, true);
11828
0
            g.OpenPopupStack.push_back(popup_ref);
11829
0
        }
11830
11831
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11832
        // This is equivalent to what ClosePopupToLevel() does.
11833
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11834
        //    FocusWindow(parent_window);
11835
0
    }
11836
0
}
11837
11838
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11839
// This function closes any popups that are over 'ref_window'.
11840
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11841
6.18k
{
11842
6.18k
    ImGuiContext& g = *GImGui;
11843
6.18k
    if (g.OpenPopupStack.Size == 0)
11844
6.18k
        return;
11845
11846
    // Don't close our own child popup windows.
11847
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11848
0
    int popup_count_to_keep = 0;
11849
0
    if (ref_window)
11850
0
    {
11851
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11852
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11853
0
        {
11854
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11855
0
            if (!popup.Window)
11856
0
                continue;
11857
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11858
11859
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11860
            // - Clicking/Focusing Window2 won't close Popup1:
11861
            //     Window -> Popup1 -> Window2(Ref)
11862
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11863
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11864
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11865
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11866
            // We step through every popup from bottom to top to validate their position relative to reference window.
11867
0
            bool ref_window_is_descendent_of_popup = false;
11868
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11869
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11870
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11871
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11872
0
                    {
11873
0
                        ref_window_is_descendent_of_popup = true;
11874
0
                        break;
11875
0
                    }
11876
0
            if (!ref_window_is_descendent_of_popup)
11877
0
                break;
11878
0
        }
11879
0
    }
11880
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11881
0
    {
11882
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11883
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11884
0
    }
11885
0
}
11886
11887
void ImGui::ClosePopupsExceptModals()
11888
0
{
11889
0
    ImGuiContext& g = *GImGui;
11890
11891
0
    int popup_count_to_keep;
11892
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11893
0
    {
11894
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11895
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11896
0
            break;
11897
0
    }
11898
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11899
0
        ClosePopupToLevel(popup_count_to_keep, true);
11900
0
}
11901
11902
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11903
0
{
11904
0
    ImGuiContext& g = *GImGui;
11905
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11906
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11907
11908
    // Trim open popup stack
11909
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11910
0
    g.OpenPopupStack.resize(remaining);
11911
11912
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11913
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11914
0
    {
11915
0
        ImGuiWindow* popup_window = prev_popup.Window;
11916
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11917
0
        if (focus_window && !focus_window->WasActive)
11918
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11919
0
        else
11920
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11921
0
    }
11922
0
}
11923
11924
// Close the popup we have begin-ed into.
11925
void ImGui::CloseCurrentPopup()
11926
0
{
11927
0
    ImGuiContext& g = *GImGui;
11928
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11929
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11930
0
        return;
11931
11932
    // Closing a menu closes its top-most parent popup (unless a modal)
11933
0
    while (popup_idx > 0)
11934
0
    {
11935
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11936
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11937
0
        bool close_parent = false;
11938
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11939
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11940
0
                close_parent = true;
11941
0
        if (!close_parent)
11942
0
            break;
11943
0
        popup_idx--;
11944
0
    }
11945
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11946
0
    ClosePopupToLevel(popup_idx, true);
11947
11948
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11949
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11950
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11951
0
    if (ImGuiWindow* window = g.NavWindow)
11952
0
        window->DC.NavHideHighlightOneFrame = true;
11953
0
}
11954
11955
// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11956
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11957
0
{
11958
0
    ImGuiContext& g = *GImGui;
11959
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11960
0
    {
11961
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11962
0
        return false;
11963
0
    }
11964
11965
0
    char name[20];
11966
0
    if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
11967
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11968
0
    else
11969
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11970
11971
0
    bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
11972
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11973
0
        EndPopup();
11974
11975
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11976
11977
0
    return is_open;
11978
0
}
11979
11980
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11981
0
{
11982
0
    ImGuiContext& g = *GImGui;
11983
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11984
0
    {
11985
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11986
0
        return false;
11987
0
    }
11988
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11989
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11990
0
    return BeginPopupEx(id, flags);
11991
0
}
11992
11993
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11994
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11995
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11996
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11997
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11998
0
{
11999
0
    ImGuiContext& g = *GImGui;
12000
0
    ImGuiWindow* window = g.CurrentWindow;
12001
0
    const ImGuiID id = window->GetID(name);
12002
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12003
0
    {
12004
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12005
0
        if (p_open && *p_open)
12006
0
            *p_open = false;
12007
0
        return false;
12008
0
    }
12009
12010
    // Center modal windows by default for increased visibility
12011
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12012
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12013
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
12014
0
    {
12015
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12016
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12017
0
    }
12018
12019
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12020
0
    const bool is_open = Begin(name, p_open, flags);
12021
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12022
0
    {
12023
0
        EndPopup();
12024
0
        if (is_open)
12025
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
12026
0
        return false;
12027
0
    }
12028
0
    return is_open;
12029
0
}
12030
12031
void ImGui::EndPopup()
12032
0
{
12033
0
    ImGuiContext& g = *GImGui;
12034
0
    ImGuiWindow* window = g.CurrentWindow;
12035
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
12036
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
12037
12038
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12039
0
    if (g.NavWindow == window)
12040
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12041
12042
    // Child-popups don't need to be laid out
12043
0
    IM_ASSERT(g.WithinEndChild == false);
12044
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
12045
0
        g.WithinEndChild = true;
12046
0
    End();
12047
0
    g.WithinEndChild = false;
12048
0
}
12049
12050
// Helper to open a popup if mouse button is released over the item
12051
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12052
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12053
0
{
12054
0
    ImGuiContext& g = *GImGui;
12055
0
    ImGuiWindow* window = g.CurrentWindow;
12056
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12057
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12058
0
    {
12059
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12060
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12061
0
        OpenPopupEx(id, popup_flags);
12062
0
    }
12063
0
}
12064
12065
// This is a helper to handle the simplest case of associating one named popup to one given widget.
12066
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12067
// - To create a popup with a specific identifier, pass it in str_id.
12068
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12069
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12070
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12071
//   This is essentially the same as:
12072
//       id = str_id ? GetID(str_id) : GetItemID();
12073
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12074
//       return BeginPopup(id);
12075
//   Which is essentially the same as:
12076
//       id = str_id ? GetID(str_id) : GetItemID();
12077
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12078
//           OpenPopup(id);
12079
//       return BeginPopup(id);
12080
//   The main difference being that this is tweaked to avoid computing the ID twice.
12081
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12082
0
{
12083
0
    ImGuiContext& g = *GImGui;
12084
0
    ImGuiWindow* window = g.CurrentWindow;
12085
0
    if (window->SkipItems)
12086
0
        return false;
12087
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12088
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12089
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12090
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12091
0
        OpenPopupEx(id, popup_flags);
12092
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12093
0
}
12094
12095
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12096
0
{
12097
0
    ImGuiContext& g = *GImGui;
12098
0
    ImGuiWindow* window = g.CurrentWindow;
12099
0
    if (!str_id)
12100
0
        str_id = "window_context";
12101
0
    ImGuiID id = window->GetID(str_id);
12102
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12103
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12104
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12105
0
            OpenPopupEx(id, popup_flags);
12106
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12107
0
}
12108
12109
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12110
0
{
12111
0
    ImGuiContext& g = *GImGui;
12112
0
    ImGuiWindow* window = g.CurrentWindow;
12113
0
    if (!str_id)
12114
0
        str_id = "void_context";
12115
0
    ImGuiID id = window->GetID(str_id);
12116
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12117
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12118
0
        if (GetTopMostPopupModal() == NULL)
12119
0
            OpenPopupEx(id, popup_flags);
12120
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12121
0
}
12122
12123
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
12124
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
12125
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12126
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12127
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
12128
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12129
0
{
12130
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12131
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12132
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12133
12134
    // Combo Box policy (we want a connecting edge)
12135
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
12136
0
    {
12137
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12138
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12139
0
        {
12140
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12141
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12142
0
                continue;
12143
0
            ImVec2 pos;
12144
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
12145
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12146
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12147
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12148
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
12149
0
                continue;
12150
0
            *last_dir = dir;
12151
0
            return pos;
12152
0
        }
12153
0
    }
12154
12155
    // Tooltip and Default popup policy
12156
    // (Always first try the direction we used on the last frame, if any)
12157
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12158
0
    {
12159
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12160
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12161
0
        {
12162
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12163
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12164
0
                continue;
12165
12166
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12167
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12168
12169
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12170
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12171
0
                continue;
12172
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12173
0
                continue;
12174
12175
0
            ImVec2 pos;
12176
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12177
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12178
12179
            // Clamp top-left corner of popup
12180
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
12181
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
12182
12183
0
            *last_dir = dir;
12184
0
            return pos;
12185
0
        }
12186
0
    }
12187
12188
    // Fallback when not enough room:
12189
0
    *last_dir = ImGuiDir_None;
12190
12191
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12192
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
12193
0
        return ref_pos + ImVec2(2, 2);
12194
12195
    // Otherwise try to keep within display
12196
0
    ImVec2 pos = ref_pos;
12197
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12198
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12199
0
    return pos;
12200
0
}
12201
12202
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12203
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12204
0
{
12205
0
    ImGuiContext& g = *GImGui;
12206
0
    ImRect r_screen;
12207
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
12208
0
    {
12209
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
12210
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
12211
0
        r_screen.Min = monitor.WorkPos;
12212
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
12213
0
    }
12214
0
    else
12215
0
    {
12216
        // Use the full viewport area (not work area) for popups
12217
0
        r_screen = window->Viewport->GetMainRect();
12218
0
    }
12219
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12220
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12221
0
    return r_screen;
12222
0
}
12223
12224
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12225
0
{
12226
0
    ImGuiContext& g = *GImGui;
12227
12228
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
12229
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
12230
0
    {
12231
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12232
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12233
0
        ImGuiWindow* parent_window = window->ParentWindow;
12234
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12235
0
        ImRect r_avoid;
12236
0
        if (parent_window->DC.MenuBarAppending)
12237
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12238
0
        else
12239
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12240
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12241
0
    }
12242
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12243
0
    {
12244
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12245
0
    }
12246
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
12247
0
    {
12248
        // Position tooltip (always follows mouse + clamp within outer boundaries)
12249
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
12250
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
12251
0
        IM_ASSERT(g.CurrentWindow == window);
12252
0
        const float scale = g.Style.MouseCursorScale;
12253
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
12254
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
12255
0
        ImRect r_avoid;
12256
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
12257
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12258
0
        else
12259
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12260
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12261
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12262
0
    }
12263
0
    IM_ASSERT(0);
12264
0
    return window->Pos;
12265
0
}
12266
12267
//-----------------------------------------------------------------------------
12268
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12269
//-----------------------------------------------------------------------------
12270
12271
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12272
// In our terminology those should be interchangeable, yet right now this is super confusing.
12273
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12274
12275
void ImGui::SetNavWindow(ImGuiWindow* window)
12276
5.72k
{
12277
5.72k
    ImGuiContext& g = *GImGui;
12278
5.72k
    if (g.NavWindow != window)
12279
5.72k
    {
12280
5.72k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12281
5.72k
        g.NavWindow = window;
12282
5.72k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12283
5.72k
    }
12284
5.72k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12285
5.72k
    NavUpdateAnyRequestFlag();
12286
5.72k
}
12287
12288
void ImGui::NavHighlightActivated(ImGuiID id)
12289
4
{
12290
4
    ImGuiContext& g = *GImGui;
12291
4
    g.NavHighlightActivatedId = id;
12292
4
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12293
4
}
12294
12295
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12296
1.44k
{
12297
1.44k
    ImGuiContext& g = *GImGui;
12298
1.44k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12299
1.44k
}
12300
12301
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12302
367
{
12303
367
    ImGuiContext& g = *GImGui;
12304
367
    IM_ASSERT(g.NavWindow != NULL);
12305
367
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12306
367
    g.NavId = id;
12307
367
    g.NavLayer = nav_layer;
12308
367
    SetNavFocusScope(focus_scope_id);
12309
367
    g.NavWindow->NavLastIds[nav_layer] = id;
12310
367
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12311
12312
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12313
367
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12314
367
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12315
367
}
12316
12317
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12318
4
{
12319
4
    ImGuiContext& g = *GImGui;
12320
4
    IM_ASSERT(id != 0);
12321
12322
4
    if (g.NavWindow != window)
12323
4
       SetNavWindow(window);
12324
12325
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12326
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12327
4
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12328
4
    g.NavId = id;
12329
4
    g.NavLayer = nav_layer;
12330
4
    SetNavFocusScope(g.CurrentFocusScopeId);
12331
4
    window->NavLastIds[nav_layer] = id;
12332
4
    if (g.LastItemData.ID == id)
12333
4
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12334
12335
4
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12336
4
        g.NavDisableMouseHover = true;
12337
0
    else
12338
0
        g.NavDisableHighlight = true;
12339
12340
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12341
4
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12342
4
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12343
4
}
12344
12345
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12346
32
{
12347
32
    if (ImFabs(dx) > ImFabs(dy))
12348
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12349
32
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12350
32
}
12351
12352
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12353
64
{
12354
64
    if (cand_max < curr_min)
12355
32
        return cand_max - curr_min;
12356
32
    if (curr_max < cand_min)
12357
0
        return cand_min - curr_max;
12358
32
    return 0.0f;
12359
32
}
12360
12361
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12362
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12363
126
{
12364
126
    ImGuiContext& g = *GImGui;
12365
126
    ImGuiWindow* window = g.CurrentWindow;
12366
126
    if (g.NavLayer != window->DC.NavLayerCurrent)
12367
94
        return false;
12368
12369
    // FIXME: Those are not good variables names
12370
32
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12371
32
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12372
32
    g.NavScoringDebugCount++;
12373
12374
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12375
32
    if (window->ParentWindow == g.NavWindow)
12376
0
    {
12377
0
        IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12378
0
        if (!window->ClipRect.Overlaps(cand))
12379
0
            return false;
12380
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12381
0
    }
12382
12383
    // Compute distance between boxes
12384
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12385
32
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12386
32
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12387
32
    if (dby != 0.0f && dbx != 0.0f)
12388
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12389
32
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12390
12391
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12392
32
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12393
32
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12394
32
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12395
12396
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12397
32
    ImGuiDir quadrant;
12398
32
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12399
32
    if (dbx != 0.0f || dby != 0.0f)
12400
32
    {
12401
        // For non-overlapping boxes, use distance between boxes
12402
32
        dax = dbx;
12403
32
        day = dby;
12404
32
        dist_axial = dist_box;
12405
32
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12406
32
    }
12407
0
    else if (dcx != 0.0f || dcy != 0.0f)
12408
0
    {
12409
        // For overlapping boxes with different centers, use distance between centers
12410
0
        dax = dcx;
12411
0
        day = dcy;
12412
0
        dist_axial = dist_center;
12413
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12414
0
    }
12415
0
    else
12416
0
    {
12417
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12418
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12419
0
    }
12420
12421
32
    const ImGuiDir move_dir = g.NavMoveDir;
12422
#if IMGUI_DEBUG_NAV_SCORING
12423
    char buf[200];
12424
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12425
    {
12426
        if (quadrant == move_dir)
12427
        {
12428
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12429
            ImDrawList* draw_list = GetForegroundDrawList(window);
12430
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12431
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12432
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12433
        }
12434
    }
12435
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12436
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12437
    if (debug_hovering || debug_tty)
12438
    {
12439
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12440
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12441
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12442
        if (debug_hovering)
12443
        {
12444
            ImDrawList* draw_list = GetForegroundDrawList(window);
12445
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12446
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12447
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12448
            draw_list->AddText(cand.Max, ~0U, buf);
12449
        }
12450
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12451
    }
12452
#endif
12453
12454
    // Is it in the quadrant we're interested in moving to?
12455
32
    bool new_best = false;
12456
32
    if (quadrant == move_dir)
12457
32
    {
12458
        // Does it beat the current best candidate?
12459
32
        if (dist_box < result->DistBox)
12460
32
        {
12461
32
            result->DistBox = dist_box;
12462
32
            result->DistCenter = dist_center;
12463
32
            return true;
12464
32
        }
12465
0
        if (dist_box == result->DistBox)
12466
0
        {
12467
            // Try using distance between center points to break ties
12468
0
            if (dist_center < result->DistCenter)
12469
0
            {
12470
0
                result->DistCenter = dist_center;
12471
0
                new_best = true;
12472
0
            }
12473
0
            else if (dist_center == result->DistCenter)
12474
0
            {
12475
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12476
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12477
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12478
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12479
0
                    new_best = true;
12480
0
            }
12481
0
        }
12482
0
    }
12483
12484
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12485
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12486
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12487
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12488
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12489
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12490
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12491
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12492
0
            {
12493
0
                result->DistAxial = dist_axial;
12494
0
                new_best = true;
12495
0
            }
12496
12497
0
    return new_best;
12498
32
}
12499
12500
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12501
144
{
12502
144
    ImGuiContext& g = *GImGui;
12503
144
    ImGuiWindow* window = g.CurrentWindow;
12504
144
    result->Window = window;
12505
144
    result->ID = g.LastItemData.ID;
12506
144
    result->FocusScopeId = g.CurrentFocusScopeId;
12507
144
    result->InFlags = g.LastItemData.InFlags;
12508
144
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12509
144
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12510
0
    {
12511
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12512
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12513
0
    }
12514
144
}
12515
12516
// True when current work location may be scrolled horizontally when moving left / right.
12517
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12518
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12519
462k
{
12520
462k
    ImGuiContext& g = *GImGui;
12521
462k
    ImGuiWindow* window = g.CurrentWindow;
12522
462k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12523
462k
}
12524
12525
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12526
// This is called after LastItemData is set, but NextItemData is also still valid.
12527
static void ImGui::NavProcessItem()
12528
558
{
12529
558
    ImGuiContext& g = *GImGui;
12530
558
    ImGuiWindow* window = g.CurrentWindow;
12531
558
    const ImGuiID id = g.LastItemData.ID;
12532
558
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12533
12534
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12535
558
    if (window->DC.NavIsScrollPushableX == false)
12536
0
    {
12537
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12538
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12539
0
    }
12540
558
    const ImRect nav_bb = g.LastItemData.NavRect;
12541
12542
    // Process Init Request
12543
558
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12544
112
    {
12545
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12546
112
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12547
112
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12548
112
        {
12549
112
            NavApplyItemToResult(&g.NavInitResult);
12550
112
        }
12551
112
        if (candidate_for_nav_default_focus)
12552
0
        {
12553
0
            g.NavInitRequest = false; // Found a match, clear request
12554
0
            NavUpdateAnyRequestFlag();
12555
0
        }
12556
112
    }
12557
12558
    // Process Move Request (scoring for navigation)
12559
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12560
558
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12561
107
    {
12562
107
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12563
107
        {
12564
107
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12565
107
            if (is_tabbing)
12566
1
            {
12567
1
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12568
1
            }
12569
106
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12570
88
            {
12571
88
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12572
88
                if (NavScoreItem(result))
12573
30
                    NavApplyItemToResult(result);
12574
12575
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12576
88
                const float VISIBLE_RATIO = 0.70f;
12577
88
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12578
38
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12579
38
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12580
2
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12581
88
            }
12582
107
        }
12583
107
    }
12584
12585
    // Update information for currently focused/navigated item
12586
558
    if (g.NavId == id)
12587
286
    {
12588
286
        if (g.NavWindow != window)
12589
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12590
286
        g.NavLayer = window->DC.NavLayerCurrent;
12591
286
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12592
286
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12593
286
        g.NavIdIsAlive = true;
12594
286
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12595
0
        {
12596
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12597
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12598
0
        }
12599
286
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12600
286
    }
12601
558
}
12602
12603
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12604
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12605
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12606
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12607
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12608
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12609
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12610
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12611
1
{
12612
1
    ImGuiContext& g = *GImGui;
12613
12614
1
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12615
1
    {
12616
1
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12617
1
            return;
12618
0
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12619
0
            return;
12620
0
    }
12621
12622
    // - Can always land on an item when using API call.
12623
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12624
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12625
0
    bool can_stop;
12626
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12627
0
        can_stop = true;
12628
0
    else
12629
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12630
12631
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12632
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12633
0
    if (g.NavTabbingDir == +1)
12634
0
    {
12635
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12636
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12637
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12638
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12639
0
            NavMoveRequestResolveWithLastItem(result);
12640
0
        else if (g.NavId == id)
12641
0
            g.NavTabbingCounter = 1;
12642
0
    }
12643
0
    else if (g.NavTabbingDir == -1)
12644
0
    {
12645
        // Tab Backward
12646
0
        if (g.NavId == id)
12647
0
        {
12648
0
            if (result->ID)
12649
0
            {
12650
0
                g.NavMoveScoringItems = false;
12651
0
                NavUpdateAnyRequestFlag();
12652
0
            }
12653
0
        }
12654
0
        else if (can_stop)
12655
0
        {
12656
            // Keep applying until reaching NavId
12657
0
            NavApplyItemToResult(result);
12658
0
        }
12659
0
    }
12660
0
    else if (g.NavTabbingDir == 0)
12661
0
    {
12662
0
        if (can_stop && g.NavId == id)
12663
0
            NavMoveRequestResolveWithLastItem(result);
12664
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12665
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12666
0
    }
12667
0
}
12668
12669
bool ImGui::NavMoveRequestButNoResultYet()
12670
10.4k
{
12671
10.4k
    ImGuiContext& g = *GImGui;
12672
10.4k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12673
10.4k
}
12674
12675
// FIXME: ScoringRect is not set
12676
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12677
855
{
12678
855
    ImGuiContext& g = *GImGui;
12679
855
    IM_ASSERT(g.NavWindow != NULL);
12680
12681
855
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12682
47
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12683
12684
855
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12685
855
    g.NavMoveDir = move_dir;
12686
855
    g.NavMoveDirForDebug = move_dir;
12687
855
    g.NavMoveClipDir = clip_dir;
12688
855
    g.NavMoveFlags = move_flags;
12689
855
    g.NavMoveScrollFlags = scroll_flags;
12690
855
    g.NavMoveForwardToNextFrame = false;
12691
855
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12692
855
    g.NavMoveResultLocal.Clear();
12693
855
    g.NavMoveResultLocalVisible.Clear();
12694
855
    g.NavMoveResultOther.Clear();
12695
855
    g.NavTabbingCounter = 0;
12696
855
    g.NavTabbingResultFirst.Clear();
12697
855
    NavUpdateAnyRequestFlag();
12698
855
}
12699
12700
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12701
0
{
12702
0
    ImGuiContext& g = *GImGui;
12703
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12704
0
    NavApplyItemToResult(result);
12705
0
    NavUpdateAnyRequestFlag();
12706
0
}
12707
12708
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12709
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12710
0
{
12711
0
    ImGuiContext& g = *GImGui;
12712
0
    g.NavMoveScoringItems = false;
12713
0
    g.LastItemData.ID = tree_node_data->ID;
12714
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12715
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12716
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12717
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12718
0
    NavUpdateAnyRequestFlag();
12719
0
}
12720
12721
void ImGui::NavMoveRequestCancel()
12722
163
{
12723
163
    ImGuiContext& g = *GImGui;
12724
163
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12725
163
    NavUpdateAnyRequestFlag();
12726
163
}
12727
12728
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12729
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12730
0
{
12731
0
    ImGuiContext& g = *GImGui;
12732
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12733
0
    NavMoveRequestCancel();
12734
0
    g.NavMoveForwardToNextFrame = true;
12735
0
    g.NavMoveDir = move_dir;
12736
0
    g.NavMoveClipDir = clip_dir;
12737
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12738
0
    g.NavMoveScrollFlags = scroll_flags;
12739
0
}
12740
12741
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12742
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12743
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12744
0
{
12745
0
    ImGuiContext& g = *GImGui;
12746
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12747
12748
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12749
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12750
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12751
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12752
0
}
12753
12754
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12755
// This way we could find the last focused window among our children. It would be much less confusing this way?
12756
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12757
7.76k
{
12758
7.76k
    ImGuiWindow* parent = nav_window;
12759
15.0k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12760
7.32k
        parent = parent->ParentWindow;
12761
7.76k
    if (parent && parent != nav_window)
12762
7.32k
        parent->NavLastChildNavWindow = nav_window;
12763
7.76k
}
12764
12765
// Restore the last focused child.
12766
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12767
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12768
61
{
12769
61
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12770
59
        return window->NavLastChildNavWindow;
12771
2
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12772
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12773
0
            return tab->Window;
12774
2
    return window;
12775
2
}
12776
12777
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12778
171
{
12779
171
    ImGuiContext& g = *GImGui;
12780
171
    if (layer == ImGuiNavLayer_Main)
12781
59
    {
12782
59
        ImGuiWindow* prev_nav_window = g.NavWindow;
12783
59
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12784
59
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12785
59
        if (prev_nav_window)
12786
59
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12787
59
    }
12788
171
    ImGuiWindow* window = g.NavWindow;
12789
171
    if (window->NavLastIds[layer] != 0)
12790
40
    {
12791
40
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12792
40
    }
12793
131
    else
12794
131
    {
12795
131
        g.NavLayer = layer;
12796
131
        NavInitWindow(window, true);
12797
131
    }
12798
171
}
12799
12800
void ImGui::NavRestoreHighlightAfterMove()
12801
566
{
12802
566
    ImGuiContext& g = *GImGui;
12803
566
    g.NavDisableHighlight = false;
12804
566
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12805
566
}
12806
12807
static inline void ImGui::NavUpdateAnyRequestFlag()
12808
145k
{
12809
145k
    ImGuiContext& g = *GImGui;
12810
145k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12811
145k
    if (g.NavAnyRequest)
12812
145k
        IM_ASSERT(g.NavWindow != NULL);
12813
145k
}
12814
12815
// This needs to be called before we submit any widget (aka in or before Begin)
12816
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12817
133
{
12818
    // FIXME: ChildWindow test here is wrong for docking
12819
133
    ImGuiContext& g = *GImGui;
12820
133
    IM_ASSERT(window == g.NavWindow);
12821
12822
133
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12823
0
    {
12824
0
        g.NavId = 0;
12825
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12826
0
        return;
12827
0
    }
12828
12829
133
    bool init_for_nav = false;
12830
133
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12831
133
        init_for_nav = true;
12832
133
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12833
133
    if (init_for_nav)
12834
133
    {
12835
133
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12836
133
        g.NavInitRequest = true;
12837
133
        g.NavInitRequestFromMove = false;
12838
133
        g.NavInitResult.ID = 0;
12839
133
        NavUpdateAnyRequestFlag();
12840
133
    }
12841
0
    else
12842
0
    {
12843
0
        g.NavId = window->NavLastIds[0];
12844
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12845
0
    }
12846
133
}
12847
12848
static ImVec2 ImGui::NavCalcPreferredRefPos()
12849
0
{
12850
0
    ImGuiContext& g = *GImGui;
12851
0
    ImGuiWindow* window = g.NavWindow;
12852
0
    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12853
12854
    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12855
0
    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12856
0
    {
12857
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12858
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12859
        // In theory we could move that +1.0f offset in OpenPopupEx()
12860
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12861
0
        return ImVec2(p.x + 1.0f, p.y);
12862
0
    }
12863
0
    else
12864
0
    {
12865
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12866
0
        ImRect ref_rect;
12867
0
        if (activated_shortcut)
12868
0
            ref_rect = g.LastItemData.NavRect;
12869
0
        else
12870
0
            ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12871
12872
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12873
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12874
0
        {
12875
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12876
0
            ref_rect.Translate(window->Scroll - next_scroll);
12877
0
        }
12878
0
        ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12879
0
        ImGuiViewport* viewport = window->Viewport;
12880
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12881
0
    }
12882
0
}
12883
12884
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12885
0
{
12886
0
    ImGuiContext& g = *GImGui;
12887
0
    float repeat_delay, repeat_rate;
12888
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12889
12890
0
    ImGuiKey key_less, key_more;
12891
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12892
0
    {
12893
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12894
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12895
0
    }
12896
0
    else
12897
0
    {
12898
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12899
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12900
0
    }
12901
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12902
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12903
0
        amount = 0.0f;
12904
0
    return amount;
12905
0
}
12906
12907
static void ImGui::NavUpdate()
12908
138k
{
12909
138k
    ImGuiContext& g = *GImGui;
12910
138k
    ImGuiIO& io = g.IO;
12911
12912
138k
    io.WantSetMousePos = false;
12913
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12914
12915
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12916
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12917
138k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12918
138k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12919
138k
    if (nav_gamepad_active)
12920
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12921
0
            if (IsKeyDown(key))
12922
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12923
138k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12924
138k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12925
138k
    if (nav_keyboard_active)
12926
138k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12927
971k
            if (IsKeyDown(key))
12928
119k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12929
12930
    // Process navigation init request (select first/default focus)
12931
138k
    g.NavJustMovedToId = 0;
12932
138k
    if (g.NavInitResult.ID != 0)
12933
112
        NavInitRequestApplyResult();
12934
138k
    g.NavInitRequest = false;
12935
138k
    g.NavInitRequestFromMove = false;
12936
138k
    g.NavInitResult.ID = 0;
12937
12938
    // Process navigation move request
12939
138k
    if (g.NavMoveSubmitted)
12940
721
        NavMoveRequestApplyResult();
12941
138k
    g.NavTabbingCounter = 0;
12942
138k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12943
12944
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12945
138k
    bool set_mouse_pos = false;
12946
138k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12947
128
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12948
120
            set_mouse_pos = true;
12949
138k
    g.NavMousePosDirty = false;
12950
138k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12951
12952
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12953
138k
    if (g.NavWindow)
12954
7.76k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12955
138k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12956
78
        g.NavWindow->NavLastChildNavWindow = NULL;
12957
12958
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12959
138k
    NavUpdateWindowing();
12960
12961
    // Set output flags for user application
12962
138k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12963
138k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12964
12965
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12966
138k
    NavUpdateCancelRequest();
12967
12968
    // Process manual activation request
12969
138k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12970
138k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12971
138k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12972
2.28k
    {
12973
2.28k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
12974
2.28k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
12975
2.28k
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
12976
2.28k
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
12977
2.28k
        if (g.ActiveId == 0 && activate_pressed)
12978
4
        {
12979
4
            g.NavActivateId = g.NavId;
12980
4
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12981
4
        }
12982
2.28k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12983
0
        {
12984
0
            g.NavActivateId = g.NavId;
12985
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12986
0
        }
12987
2.28k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12988
478
            g.NavActivateDownId = g.NavId;
12989
2.28k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12990
4
        {
12991
4
            g.NavActivatePressedId = g.NavId;
12992
4
            NavHighlightActivated(g.NavId);
12993
4
        }
12994
2.28k
    }
12995
138k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12996
0
        g.NavDisableHighlight = true;
12997
138k
    if (g.NavActivateId != 0)
12998
138k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12999
13000
    // Highlight
13001
138k
    if (g.NavHighlightActivatedTimer > 0.0f)
13002
28
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
13003
138k
    if (g.NavHighlightActivatedTimer == 0.0f)
13004
138k
        g.NavHighlightActivatedId = 0;
13005
13006
    // Process programmatic activation request
13007
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
13008
138k
    if (g.NavNextActivateId != 0)
13009
0
    {
13010
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
13011
0
        g.NavActivateFlags = g.NavNextActivateFlags;
13012
0
    }
13013
138k
    g.NavNextActivateId = 0;
13014
13015
    // Process move requests
13016
138k
    NavUpdateCreateMoveRequest();
13017
138k
    if (g.NavMoveDir == ImGuiDir_None)
13018
138k
        NavUpdateCreateTabbingRequest();
13019
138k
    NavUpdateAnyRequestFlag();
13020
138k
    g.NavIdIsAlive = false;
13021
13022
    // Scrolling
13023
138k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
13024
7.76k
    {
13025
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
13026
7.76k
        ImGuiWindow* window = g.NavWindow;
13027
7.76k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
13028
7.76k
        const ImGuiDir move_dir = g.NavMoveDir;
13029
7.76k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
13030
644
        {
13031
644
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
13032
149
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
13033
644
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
13034
495
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
13035
644
        }
13036
13037
        // *Normal* Manual scroll with LStick
13038
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
13039
7.76k
        if (nav_gamepad_active)
13040
0
        {
13041
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13042
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
13043
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
13044
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
13045
0
            if (scroll_dir.y != 0.0f)
13046
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
13047
0
        }
13048
7.76k
    }
13049
13050
    // Always prioritize mouse highlight if navigation is disabled
13051
138k
    if (!nav_keyboard_active && !nav_gamepad_active)
13052
0
    {
13053
0
        g.NavDisableHighlight = true;
13054
0
        g.NavDisableMouseHover = set_mouse_pos = false;
13055
0
    }
13056
13057
    // Update mouse position if requested
13058
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
13059
138k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
13060
0
        TeleportMousePos(NavCalcPreferredRefPos());
13061
13062
    // [DEBUG]
13063
138k
    g.NavScoringDebugCount = 0;
13064
#if IMGUI_DEBUG_NAV_RECTS
13065
    if (ImGuiWindow* debug_window = g.NavWindow)
13066
    {
13067
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
13068
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
13069
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
13070
    }
13071
#endif
13072
138k
}
13073
13074
void ImGui::NavInitRequestApplyResult()
13075
112
{
13076
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
13077
112
    ImGuiContext& g = *GImGui;
13078
112
    if (!g.NavWindow)
13079
30
        return;
13080
13081
82
    ImGuiNavItemData* result = &g.NavInitResult;
13082
82
    if (g.NavId != result->ID)
13083
79
    {
13084
79
        g.NavJustMovedToId = result->ID;
13085
79
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13086
79
        g.NavJustMovedToKeyMods = 0;
13087
79
        g.NavJustMovedToIsTabbing = false;
13088
79
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13089
79
    }
13090
13091
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
13092
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
13093
82
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13094
82
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13095
82
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13096
82
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13097
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13098
82
    if (g.NavInitRequestFromMove)
13099
0
        NavRestoreHighlightAfterMove();
13100
82
}
13101
13102
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13103
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13104
808
{
13105
    // Bias initial rect
13106
808
    ImGuiContext& g = *GImGui;
13107
808
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13108
13109
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13110
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13111
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
13112
808
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13113
808
    {
13114
808
        if (preferred_pos_rel.x == FLT_MAX)
13115
206
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13116
808
        if (preferred_pos_rel.y == FLT_MAX)
13117
572
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13118
808
    }
13119
13120
    // Apply general bias on the other axis
13121
808
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13122
612
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13123
196
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13124
196
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13125
808
}
13126
13127
void ImGui::NavUpdateCreateMoveRequest()
13128
138k
{
13129
138k
    ImGuiContext& g = *GImGui;
13130
138k
    ImGuiIO& io = g.IO;
13131
138k
    ImGuiWindow* window = g.NavWindow;
13132
138k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13133
138k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13134
13135
138k
    if (g.NavMoveForwardToNextFrame && window != NULL)
13136
0
    {
13137
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13138
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
13139
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13140
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13141
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13142
0
    }
13143
138k
    else
13144
138k
    {
13145
        // Initiate directional inputs request
13146
138k
        g.NavMoveDir = ImGuiDir_None;
13147
138k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
13148
138k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13149
138k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13150
7.76k
        {
13151
7.76k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13152
7.76k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13153
7.76k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13154
7.76k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13155
7.76k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13156
7.76k
        }
13157
138k
        g.NavMoveClipDir = g.NavMoveDir;
13158
138k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13159
138k
    }
13160
13161
    // Update PageUp/PageDown/Home/End scroll
13162
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13163
138k
    float scoring_rect_offset_y = 0.0f;
13164
138k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13165
7.00k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
13166
138k
    if (scoring_rect_offset_y != 0.0f)
13167
47
    {
13168
47
        g.NavScoringNoClipRect = window->InnerRect;
13169
47
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13170
47
    }
13171
13172
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13173
#if IMGUI_DEBUG_NAV_SCORING
13174
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13175
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13176
    if (io.KeyCtrl)
13177
    {
13178
        if (g.NavMoveDir == ImGuiDir_None)
13179
            g.NavMoveDir = g.NavMoveDirForDebug;
13180
        g.NavMoveClipDir = g.NavMoveDir;
13181
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13182
    }
13183
#endif
13184
13185
    // Submit
13186
138k
    g.NavMoveForwardToNextFrame = false;
13187
138k
    if (g.NavMoveDir != ImGuiDir_None)
13188
808
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13189
13190
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13191
138k
    if (g.NavMoveSubmitted && g.NavId == 0)
13192
459
    {
13193
459
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13194
459
        g.NavInitRequest = g.NavInitRequestFromMove = true;
13195
459
        g.NavInitResult.ID = 0;
13196
459
        g.NavDisableHighlight = false;
13197
459
    }
13198
13199
    // When using gamepad, we project the reference nav bounding box into window visible area.
13200
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13201
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13202
138k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13203
0
    {
13204
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13205
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13206
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13207
13208
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13209
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
13210
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13211
13212
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13213
0
        {
13214
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13215
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13216
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13217
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13218
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13219
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13220
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13221
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13222
0
            g.NavId = 0;
13223
0
        }
13224
0
    }
13225
13226
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13227
138k
    ImRect scoring_rect;
13228
138k
    if (window != NULL)
13229
7.76k
    {
13230
7.76k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13231
7.76k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13232
7.76k
        scoring_rect.TranslateY(scoring_rect_offset_y);
13233
7.76k
        if (g.NavMoveSubmitted)
13234
808
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13235
7.76k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13236
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13237
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13238
7.76k
    }
13239
138k
    g.NavScoringRect = scoring_rect;
13240
138k
    g.NavScoringNoClipRect.Add(scoring_rect);
13241
138k
}
13242
13243
void ImGui::NavUpdateCreateTabbingRequest()
13244
138k
{
13245
138k
    ImGuiContext& g = *GImGui;
13246
138k
    ImGuiWindow* window = g.NavWindow;
13247
138k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13248
138k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13249
131k
        return;
13250
13251
6.96k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13252
6.96k
    if (!tab_pressed)
13253
6.91k
        return;
13254
13255
    // Initiate tabbing request
13256
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13257
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13258
47
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13259
47
    if (nav_keyboard_active)
13260
47
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
13261
0
    else
13262
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13263
47
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13264
47
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13265
47
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13266
47
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13267
47
    g.NavTabbingCounter = -1;
13268
47
}
13269
13270
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13271
void ImGui::NavMoveRequestApplyResult()
13272
721
{
13273
721
    ImGuiContext& g = *GImGui;
13274
#if IMGUI_DEBUG_NAV_SCORING
13275
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13276
        return;
13277
#endif
13278
13279
    // Select which result to use
13280
721
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13281
13282
    // Tabbing forward wrap
13283
721
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13284
35
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13285
0
            result = &g.NavTabbingResultFirst;
13286
13287
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13288
721
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13289
721
    if (result == NULL)
13290
704
    {
13291
704
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13292
35
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
13293
704
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13294
285
            NavRestoreHighlightAfterMove();
13295
704
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13296
704
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13297
704
        return;
13298
704
    }
13299
13300
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13301
17
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13302
17
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13303
0
            result = &g.NavMoveResultLocalVisible;
13304
13305
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13306
17
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13307
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13308
0
            result = &g.NavMoveResultOther;
13309
17
    IM_ASSERT(g.NavWindow && result->Window);
13310
13311
    // Scroll to keep newly navigated item fully into view.
13312
17
    if (g.NavLayer == ImGuiNavLayer_Main)
13313
17
    {
13314
17
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13315
17
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13316
13317
17
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13318
0
        {
13319
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13320
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13321
0
            SetScrollY(result->Window, scroll_target);
13322
0
        }
13323
17
    }
13324
13325
17
    if (g.NavWindow != result->Window)
13326
0
    {
13327
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13328
0
        g.NavWindow = result->Window;
13329
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13330
0
    }
13331
13332
    // Clear active id unless requested not to
13333
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13334
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13335
17
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13336
17
        ClearActiveID();
13337
13338
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13339
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13340
17
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13341
17
    {
13342
17
        g.NavJustMovedToId = result->ID;
13343
17
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13344
17
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13345
17
        g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13346
17
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13347
        //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13348
17
    }
13349
13350
    // Apply new NavID/Focus
13351
17
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13352
17
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13353
17
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13354
17
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13355
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13356
13357
    // Restore last preferred position for current axis
13358
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13359
17
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13360
17
    {
13361
17
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13362
17
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13363
17
    }
13364
13365
    // Tabbing: Activates Inputable, otherwise only Focus
13366
17
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13367
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13368
13369
    // Activate
13370
17
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13371
0
    {
13372
0
        g.NavNextActivateId = result->ID;
13373
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13374
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13375
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13376
0
    }
13377
13378
    // Enable nav highlight
13379
17
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13380
17
        NavRestoreHighlightAfterMove();
13381
17
}
13382
13383
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13384
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13385
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13386
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13387
static void ImGui::NavUpdateCancelRequest()
13388
138k
{
13389
138k
    ImGuiContext& g = *GImGui;
13390
138k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13391
138k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13392
138k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13393
136k
        return;
13394
13395
2.40k
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13396
2.40k
    if (g.ActiveId != 0)
13397
1
    {
13398
1
        ClearActiveID();
13399
1
    }
13400
2.40k
    else if (g.NavLayer != ImGuiNavLayer_Main)
13401
0
    {
13402
        // Leave the "menu" layer
13403
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13404
0
        NavRestoreHighlightAfterMove();
13405
0
    }
13406
2.40k
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13407
95
    {
13408
        // Exit child window
13409
95
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13410
95
        ImGuiWindow* parent_window = child_window->ParentWindow;
13411
95
        IM_ASSERT(child_window->ChildId != 0);
13412
95
        FocusWindow(parent_window);
13413
95
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13414
95
        NavRestoreHighlightAfterMove();
13415
95
    }
13416
2.30k
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13417
0
    {
13418
        // Close open popup/menu
13419
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13420
0
    }
13421
2.30k
    else
13422
2.30k
    {
13423
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13424
2.30k
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13425
1
            g.NavWindow->NavLastIds[0] = 0;
13426
2.30k
        g.NavId = 0;
13427
2.30k
    }
13428
2.40k
}
13429
13430
// Handle PageUp/PageDown/Home/End keys
13431
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13432
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13433
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13434
static float ImGui::NavUpdatePageUpPageDown()
13435
7.00k
{
13436
7.00k
    ImGuiContext& g = *GImGui;
13437
7.00k
    ImGuiWindow* window = g.NavWindow;
13438
7.00k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13439
0
        return 0.0f;
13440
13441
7.00k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13442
7.00k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13443
7.00k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13444
7.00k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13445
7.00k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13446
6.28k
        return 0.0f;
13447
13448
720
    if (g.NavLayer != ImGuiNavLayer_Main)
13449
2
        NavRestoreLayer(ImGuiNavLayer_Main);
13450
13451
720
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13452
531
    {
13453
        // Fallback manual-scroll when window has no navigable item
13454
531
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13455
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13456
531
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13457
35
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13458
496
        else if (home_pressed)
13459
2
            SetScrollY(window, 0.0f);
13460
494
        else if (end_pressed)
13461
0
            SetScrollY(window, window->ScrollMax.y);
13462
531
    }
13463
189
    else
13464
189
    {
13465
189
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13466
189
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13467
189
        float nav_scoring_rect_offset_y = 0.0f;
13468
189
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13469
0
        {
13470
0
            nav_scoring_rect_offset_y = -page_offset_y;
13471
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13472
0
            g.NavMoveClipDir = ImGuiDir_Up;
13473
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13474
0
        }
13475
189
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13476
47
        {
13477
47
            nav_scoring_rect_offset_y = +page_offset_y;
13478
47
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13479
47
            g.NavMoveClipDir = ImGuiDir_Down;
13480
47
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13481
47
        }
13482
142
        else if (home_pressed)
13483
2
        {
13484
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13485
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13486
            // Preserve current horizontal position if we have any.
13487
2
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13488
2
            if (nav_rect_rel.IsInverted())
13489
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13490
2
            g.NavMoveDir = ImGuiDir_Down;
13491
2
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13492
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13493
2
        }
13494
140
        else if (end_pressed)
13495
0
        {
13496
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13497
0
            if (nav_rect_rel.IsInverted())
13498
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13499
0
            g.NavMoveDir = ImGuiDir_Up;
13500
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13501
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13502
0
        }
13503
189
        return nav_scoring_rect_offset_y;
13504
189
    }
13505
531
    return 0.0f;
13506
720
}
13507
13508
static void ImGui::NavEndFrame()
13509
138k
{
13510
138k
    ImGuiContext& g = *GImGui;
13511
13512
    // Show CTRL+TAB list window
13513
138k
    if (g.NavWindowingTarget != NULL)
13514
0
        NavUpdateWindowingOverlay();
13515
13516
    // Perform wrap-around in menus
13517
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13518
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13519
138k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13520
0
        NavUpdateCreateWrappingRequest();
13521
138k
}
13522
13523
static void ImGui::NavUpdateCreateWrappingRequest()
13524
0
{
13525
0
    ImGuiContext& g = *GImGui;
13526
0
    ImGuiWindow* window = g.NavWindow;
13527
13528
0
    bool do_forward = false;
13529
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13530
0
    ImGuiDir clip_dir = g.NavMoveDir;
13531
13532
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13533
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13534
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13535
0
    {
13536
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13537
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13538
0
        {
13539
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13540
0
            clip_dir = ImGuiDir_Up;
13541
0
        }
13542
0
        do_forward = true;
13543
0
    }
13544
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13545
0
    {
13546
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13547
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13548
0
        {
13549
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13550
0
            clip_dir = ImGuiDir_Down;
13551
0
        }
13552
0
        do_forward = true;
13553
0
    }
13554
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13555
0
    {
13556
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13557
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13558
0
        {
13559
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13560
0
            clip_dir = ImGuiDir_Left;
13561
0
        }
13562
0
        do_forward = true;
13563
0
    }
13564
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13565
0
    {
13566
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13567
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13568
0
        {
13569
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13570
0
            clip_dir = ImGuiDir_Right;
13571
0
        }
13572
0
        do_forward = true;
13573
0
    }
13574
0
    if (!do_forward)
13575
0
        return;
13576
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13577
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13578
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13579
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13580
0
}
13581
13582
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13583
0
{
13584
0
    ImGuiContext& g = *GImGui;
13585
0
    IM_UNUSED(g);
13586
0
    int order = window->FocusOrder;
13587
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13588
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13589
0
    return order;
13590
0
}
13591
13592
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13593
0
{
13594
0
    ImGuiContext& g = *GImGui;
13595
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13596
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13597
0
            return g.WindowsFocusOrder[i];
13598
0
    return NULL;
13599
0
}
13600
13601
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13602
0
{
13603
0
    ImGuiContext& g = *GImGui;
13604
0
    IM_ASSERT(g.NavWindowingTarget);
13605
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13606
0
        return;
13607
13608
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13609
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13610
0
    if (!window_target)
13611
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13612
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13613
0
    {
13614
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13615
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13616
0
    }
13617
0
    g.NavWindowingToggleLayer = false;
13618
0
}
13619
13620
// Windowing management mode
13621
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13622
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13623
static void ImGui::NavUpdateWindowing()
13624
138k
{
13625
138k
    ImGuiContext& g = *GImGui;
13626
138k
    ImGuiIO& io = g.IO;
13627
13628
138k
    ImGuiWindow* apply_focus_window = NULL;
13629
138k
    bool apply_toggle_layer = false;
13630
13631
138k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13632
138k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13633
138k
    if (!allow_windowing)
13634
0
        g.NavWindowingTarget = NULL;
13635
13636
    // Fade out
13637
138k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13638
0
    {
13639
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13640
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13641
0
            g.NavWindowingTargetAnim = NULL;
13642
0
    }
13643
13644
    // Start CTRL+Tab or Square+L/R window selection
13645
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13646
138k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13647
138k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13648
138k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13649
138k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13650
138k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13651
138k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13652
138k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13653
138k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13654
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13655
0
        {
13656
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13657
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13658
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13659
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13660
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13661
13662
            // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13663
0
            if (keyboard_next_window || keyboard_prev_window)
13664
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13665
0
        }
13666
13667
    // Gamepad update
13668
138k
    g.NavWindowingTimer += io.DeltaTime;
13669
138k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13670
0
    {
13671
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13672
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13673
13674
        // Select window to focus
13675
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13676
0
        if (focus_change_dir != 0)
13677
0
        {
13678
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13679
0
            g.NavWindowingHighlightAlpha = 1.0f;
13680
0
        }
13681
13682
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13683
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13684
0
        {
13685
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13686
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13687
0
                apply_toggle_layer = true;
13688
0
            else if (!g.NavWindowingToggleLayer)
13689
0
                apply_focus_window = g.NavWindowingTarget;
13690
0
            g.NavWindowingTarget = NULL;
13691
0
        }
13692
0
    }
13693
13694
    // Keyboard: Focus
13695
138k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13696
0
    {
13697
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13698
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13699
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13700
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13701
0
        if (keyboard_next_window || keyboard_prev_window)
13702
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13703
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13704
0
            apply_focus_window = g.NavWindowingTarget;
13705
0
    }
13706
13707
    // Keyboard: Press and Release ALT to toggle menu layer
13708
138k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13709
138k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13710
277k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13711
1.67k
        {
13712
1.67k
            g.NavWindowingToggleLayer = true;
13713
1.67k
            g.NavWindowingToggleKey = windowing_toggle_key;
13714
1.67k
            g.NavInputSource = ImGuiInputSource_Keyboard;
13715
1.67k
            break;
13716
1.67k
        }
13717
138k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13718
5.91k
    {
13719
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13720
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13721
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13722
        // We cancel toggling nav layer if an owner has claimed the key.
13723
5.91k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13724
257
            g.NavWindowingToggleLayer = false;
13725
5.91k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13726
0
            g.NavWindowingToggleLayer = false;
13727
13728
        // Apply layer toggle on Alt release
13729
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13730
5.91k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13731
1.04k
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13732
1.04k
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13733
1.04k
                    apply_toggle_layer = true;
13734
5.91k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13735
1.60k
            g.NavWindowingToggleLayer = false;
13736
5.91k
    }
13737
13738
    // Move window
13739
138k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13740
0
    {
13741
0
        ImVec2 nav_move_dir;
13742
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13743
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13744
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13745
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13746
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13747
0
        {
13748
0
            const float NAV_MOVE_SPEED = 800.0f;
13749
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13750
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13751
0
            g.NavDisableMouseHover = true;
13752
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13753
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13754
0
            {
13755
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13756
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13757
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13758
0
            }
13759
0
        }
13760
0
    }
13761
13762
    // Apply final focus
13763
138k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13764
0
    {
13765
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13766
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13767
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13768
0
        ClearActiveID();
13769
0
        NavRestoreHighlightAfterMove();
13770
0
        ClosePopupsOverWindow(apply_focus_window, false);
13771
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13772
0
        apply_focus_window = g.NavWindow;
13773
0
        if (apply_focus_window->NavLastIds[0] == 0)
13774
0
            NavInitWindow(apply_focus_window, false);
13775
13776
        // If the window has ONLY a menu layer (no main layer), select it directly
13777
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13778
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13779
        // the target window as already been previewed once.
13780
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13781
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13782
        // won't be valid.
13783
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13784
0
            g.NavLayer = ImGuiNavLayer_Menu;
13785
13786
        // Request OS level focus
13787
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13788
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13789
0
    }
13790
138k
    if (apply_focus_window)
13791
0
        g.NavWindowingTarget = NULL;
13792
13793
    // Apply menu/layer toggle
13794
138k
    if (apply_toggle_layer && g.NavWindow)
13795
169
    {
13796
169
        ClearActiveID();
13797
13798
        // Move to parent menu if necessary
13799
169
        ImGuiWindow* new_nav_window = g.NavWindow;
13800
281
        while (new_nav_window->ParentWindow
13801
281
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13802
281
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13803
281
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13804
112
            new_nav_window = new_nav_window->ParentWindow;
13805
169
        if (new_nav_window != g.NavWindow)
13806
112
        {
13807
112
            ImGuiWindow* old_nav_window = g.NavWindow;
13808
112
            FocusWindow(new_nav_window);
13809
112
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13810
112
        }
13811
13812
        // Toggle layer
13813
169
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13814
169
        if (new_nav_layer != g.NavLayer)
13815
169
        {
13816
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13817
169
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13818
169
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13819
112
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13820
169
            NavRestoreLayer(new_nav_layer);
13821
169
            NavRestoreHighlightAfterMove();
13822
169
        }
13823
169
    }
13824
138k
}
13825
13826
// Window has already passed the IsWindowNavFocusable()
13827
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13828
0
{
13829
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13830
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13831
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13832
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13833
0
    if (window->DockNodeAsHost)
13834
0
        return "(Dock node)"; // Not normally shown to user.
13835
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13836
0
}
13837
13838
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13839
void ImGui::NavUpdateWindowingOverlay()
13840
0
{
13841
0
    ImGuiContext& g = *GImGui;
13842
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13843
13844
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13845
0
        return;
13846
13847
0
    if (g.NavWindowingListWindow == NULL)
13848
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13849
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13850
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13851
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13852
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13853
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13854
0
    if (g.ContextName[0] != 0)
13855
0
        SeparatorText(g.ContextName);
13856
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13857
0
    {
13858
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13859
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13860
0
        if (!IsWindowNavFocusable(window))
13861
0
            continue;
13862
0
        const char* label = window->Name;
13863
0
        if (label == FindRenderedTextEnd(label))
13864
0
            label = GetFallbackWindowNameForWindowingList(window);
13865
0
        Selectable(label, g.NavWindowingTarget == window);
13866
0
    }
13867
0
    End();
13868
0
    PopStyleVar();
13869
0
}
13870
13871
13872
//-----------------------------------------------------------------------------
13873
// [SECTION] DRAG AND DROP
13874
//-----------------------------------------------------------------------------
13875
13876
bool ImGui::IsDragDropActive()
13877
0
{
13878
0
    ImGuiContext& g = *GImGui;
13879
0
    return g.DragDropActive;
13880
0
}
13881
13882
void ImGui::ClearDragDrop()
13883
4
{
13884
4
    ImGuiContext& g = *GImGui;
13885
4
    if (g.DragDropActive)
13886
2
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13887
4
    g.DragDropActive = false;
13888
4
    g.DragDropPayload.Clear();
13889
4
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13890
4
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13891
4
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13892
4
    g.DragDropAcceptFrameCount = -1;
13893
13894
4
    g.DragDropPayloadBufHeap.clear();
13895
4
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13896
4
}
13897
13898
bool ImGui::BeginTooltipHidden()
13899
0
{
13900
0
    ImGuiContext& g = *GImGui;
13901
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13902
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13903
0
    return ret;
13904
0
}
13905
13906
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13907
// If the item has an identifier:
13908
// - This assume/require the item to be activated (typically via ButtonBehavior).
13909
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13910
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13911
// If the item has no identifier:
13912
// - Currently always assume left mouse button.
13913
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13914
136
{
13915
136
    ImGuiContext& g = *GImGui;
13916
136
    ImGuiWindow* window = g.CurrentWindow;
13917
13918
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13919
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13920
136
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13921
13922
136
    bool source_drag_active = false;
13923
136
    ImGuiID source_id = 0;
13924
136
    ImGuiID source_parent_id = 0;
13925
136
    if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13926
136
    {
13927
136
        source_id = g.LastItemData.ID;
13928
136
        if (source_id != 0)
13929
136
        {
13930
            // Common path: items with ID
13931
136
            if (g.ActiveId != source_id)
13932
0
                return false;
13933
136
            if (g.ActiveIdMouseButton != -1)
13934
0
                mouse_button = g.ActiveIdMouseButton;
13935
136
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13936
0
                return false;
13937
136
            g.ActiveIdAllowOverlap = false;
13938
136
        }
13939
0
        else
13940
0
        {
13941
            // Uncommon path: items without ID
13942
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13943
0
                return false;
13944
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13945
0
                return false;
13946
13947
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13948
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13949
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13950
0
            {
13951
0
                IM_ASSERT(0);
13952
0
                return false;
13953
0
            }
13954
13955
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13956
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13957
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13958
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13959
            // Rely on keeping other window->LastItemXXX fields intact.
13960
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13961
0
            KeepAliveID(source_id);
13962
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13963
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13964
0
            {
13965
0
                SetActiveID(source_id, window);
13966
0
                FocusWindow(window);
13967
0
            }
13968
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13969
0
                g.ActiveIdAllowOverlap = is_hovered;
13970
0
        }
13971
136
        if (g.ActiveId != source_id)
13972
0
            return false;
13973
136
        source_parent_id = window->IDStack.back();
13974
136
        source_drag_active = IsMouseDragging(mouse_button);
13975
13976
        // Disable navigation and key inputs while dragging + cancel existing request if any
13977
136
        SetActiveIdUsingAllKeyboardKeys();
13978
136
    }
13979
0
    else
13980
0
    {
13981
        // When ImGuiDragDropFlags_SourceExtern is set:
13982
0
        window = NULL;
13983
0
        source_id = ImHashStr("#SourceExtern");
13984
0
        source_drag_active = true;
13985
0
        mouse_button = g.IO.MouseDown[0] ? 0 : -1;
13986
0
        KeepAliveID(source_id);
13987
0
        SetActiveID(source_id, NULL);
13988
0
    }
13989
13990
136
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13991
136
    if (!source_drag_active)
13992
41
        return false;
13993
13994
    // Activate drag and drop
13995
95
    if (!g.DragDropActive)
13996
2
    {
13997
2
        IM_ASSERT(source_id != 0);
13998
2
        ClearDragDrop();
13999
2
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
14000
2
            source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
14001
2
        ImGuiPayload& payload = g.DragDropPayload;
14002
2
        payload.SourceId = source_id;
14003
2
        payload.SourceParentId = source_parent_id;
14004
2
        g.DragDropActive = true;
14005
2
        g.DragDropSourceFlags = flags;
14006
2
        g.DragDropMouseButton = mouse_button;
14007
2
        if (payload.SourceId == g.ActiveId)
14008
2
            g.ActiveIdNoClearOnFocusLoss = true;
14009
2
    }
14010
95
    g.DragDropSourceFrameCount = g.FrameCount;
14011
95
    g.DragDropWithinSource = true;
14012
14013
95
    if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14014
0
    {
14015
        // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
14016
        // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
14017
0
        bool ret;
14018
0
        if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
14019
0
            ret = BeginTooltipHidden();
14020
0
        else
14021
0
            ret = BeginTooltip();
14022
0
        IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
14023
0
        IM_UNUSED(ret);
14024
0
    }
14025
14026
95
    if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
14027
95
        g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
14028
14029
95
    return true;
14030
136
}
14031
14032
void ImGui::EndDragDropSource()
14033
95
{
14034
95
    ImGuiContext& g = *GImGui;
14035
95
    IM_ASSERT(g.DragDropActive);
14036
95
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
14037
14038
95
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14039
0
        EndTooltip();
14040
14041
    // Discard the drag if have not called SetDragDropPayload()
14042
95
    if (g.DragDropPayload.DataFrameCount == -1)
14043
0
        ClearDragDrop();
14044
95
    g.DragDropWithinSource = false;
14045
95
}
14046
14047
// Use 'cond' to choose to submit payload on drag start or every frame
14048
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
14049
95
{
14050
95
    ImGuiContext& g = *GImGui;
14051
95
    ImGuiPayload& payload = g.DragDropPayload;
14052
95
    if (cond == 0)
14053
95
        cond = ImGuiCond_Always;
14054
14055
95
    IM_ASSERT(type != NULL);
14056
95
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
14057
95
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
14058
95
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
14059
95
    IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
14060
14061
95
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
14062
95
    {
14063
        // Copy payload
14064
95
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
14065
95
        g.DragDropPayloadBufHeap.resize(0);
14066
95
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
14067
0
        {
14068
            // Store in heap
14069
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
14070
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
14071
0
            memcpy(payload.Data, data, data_size);
14072
0
        }
14073
95
        else if (data_size > 0)
14074
95
        {
14075
            // Store locally
14076
95
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
14077
95
            payload.Data = g.DragDropPayloadBufLocal;
14078
95
            memcpy(payload.Data, data, data_size);
14079
95
        }
14080
0
        else
14081
0
        {
14082
0
            payload.Data = NULL;
14083
0
        }
14084
95
        payload.DataSize = (int)data_size;
14085
95
    }
14086
95
    payload.DataFrameCount = g.FrameCount;
14087
14088
    // Return whether the payload has been accepted
14089
95
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14090
95
}
14091
14092
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14093
101
{
14094
101
    ImGuiContext& g = *GImGui;
14095
101
    if (!g.DragDropActive)
14096
0
        return false;
14097
14098
101
    ImGuiWindow* window = g.CurrentWindow;
14099
101
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14100
101
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
14101
99
        return false;
14102
2
    IM_ASSERT(id != 0);
14103
2
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14104
0
        return false;
14105
2
    if (window->SkipItems)
14106
0
        return false;
14107
14108
2
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14109
2
    g.DragDropTargetRect = bb;
14110
2
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
14111
2
    g.DragDropTargetId = id;
14112
2
    g.DragDropWithinTarget = true;
14113
2
    return true;
14114
2
}
14115
14116
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
14117
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14118
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14119
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14120
bool ImGui::BeginDragDropTarget()
14121
0
{
14122
0
    ImGuiContext& g = *GImGui;
14123
0
    if (!g.DragDropActive)
14124
0
        return false;
14125
14126
0
    ImGuiWindow* window = g.CurrentWindow;
14127
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14128
0
        return false;
14129
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14130
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
14131
0
        return false;
14132
14133
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14134
0
    ImGuiID id = g.LastItemData.ID;
14135
0
    if (id == 0)
14136
0
    {
14137
0
        id = window->GetIDFromRectangle(display_rect);
14138
0
        KeepAliveID(id);
14139
0
    }
14140
0
    if (g.DragDropPayload.SourceId == id)
14141
0
        return false;
14142
14143
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14144
0
    g.DragDropTargetRect = display_rect;
14145
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14146
0
    g.DragDropTargetId = id;
14147
0
    g.DragDropWithinTarget = true;
14148
0
    return true;
14149
0
}
14150
14151
bool ImGui::IsDragDropPayloadBeingAccepted()
14152
26
{
14153
26
    ImGuiContext& g = *GImGui;
14154
26
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14155
26
}
14156
14157
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14158
2
{
14159
2
    ImGuiContext& g = *GImGui;
14160
2
    ImGuiPayload& payload = g.DragDropPayload;
14161
2
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14162
2
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
14163
2
    if (type != NULL && !payload.IsDataType(type))
14164
0
        return NULL;
14165
14166
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14167
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14168
2
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14169
2
    ImRect r = g.DragDropTargetRect;
14170
2
    float r_surface = r.GetWidth() * r.GetHeight();
14171
2
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14172
0
        return NULL;
14173
14174
2
    g.DragDropAcceptFlags = flags;
14175
2
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
14176
2
    g.DragDropAcceptIdCurrRectSurface = r_surface;
14177
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14178
14179
    // Render default drop visuals
14180
2
    payload.Preview = was_accepted_previously;
14181
2
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14182
2
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14183
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14184
14185
2
    g.DragDropAcceptFrameCount = g.FrameCount;
14186
2
    if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14187
0
        payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14188
2
    else
14189
2
        payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14190
2
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14191
0
        return NULL;
14192
14193
2
    if (payload.Delivery)
14194
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14195
2
    return &payload;
14196
2
}
14197
14198
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14199
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14200
0
{
14201
0
    ImGuiContext& g = *GImGui;
14202
0
    ImGuiWindow* window = g.CurrentWindow;
14203
0
    ImRect bb_display = bb;
14204
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14205
0
    bb_display.Expand(3.5f);
14206
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14207
0
    if (push_clip_rect)
14208
0
        window->DrawList->PushClipRectFullScreen();
14209
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14210
0
    if (push_clip_rect)
14211
0
        window->DrawList->PopClipRect();
14212
0
}
14213
14214
const ImGuiPayload* ImGui::GetDragDropPayload()
14215
0
{
14216
0
    ImGuiContext& g = *GImGui;
14217
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14218
0
}
14219
14220
void ImGui::EndDragDropTarget()
14221
2
{
14222
2
    ImGuiContext& g = *GImGui;
14223
2
    IM_ASSERT(g.DragDropActive);
14224
2
    IM_ASSERT(g.DragDropWithinTarget);
14225
2
    g.DragDropWithinTarget = false;
14226
14227
    // Clear drag and drop state payload right after delivery
14228
2
    if (g.DragDropPayload.Delivery)
14229
0
        ClearDragDrop();
14230
2
}
14231
14232
//-----------------------------------------------------------------------------
14233
// [SECTION] LOGGING/CAPTURING
14234
//-----------------------------------------------------------------------------
14235
// All text output from the interface can be captured into tty/file/clipboard.
14236
// By default, tree nodes are automatically opened during logging.
14237
//-----------------------------------------------------------------------------
14238
14239
// Pass text data straight to log (without being displayed)
14240
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14241
0
{
14242
0
    if (g.LogFile)
14243
0
    {
14244
0
        g.LogBuffer.Buf.resize(0);
14245
0
        g.LogBuffer.appendfv(fmt, args);
14246
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14247
0
    }
14248
0
    else
14249
0
    {
14250
0
        g.LogBuffer.appendfv(fmt, args);
14251
0
    }
14252
0
}
14253
14254
void ImGui::LogText(const char* fmt, ...)
14255
0
{
14256
0
    ImGuiContext& g = *GImGui;
14257
0
    if (!g.LogEnabled)
14258
0
        return;
14259
14260
0
    va_list args;
14261
0
    va_start(args, fmt);
14262
0
    LogTextV(g, fmt, args);
14263
0
    va_end(args);
14264
0
}
14265
14266
void ImGui::LogTextV(const char* fmt, va_list args)
14267
0
{
14268
0
    ImGuiContext& g = *GImGui;
14269
0
    if (!g.LogEnabled)
14270
0
        return;
14271
14272
0
    LogTextV(g, fmt, args);
14273
0
}
14274
14275
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
14276
// We split text into individual lines to add current tree level padding
14277
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14278
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14279
0
{
14280
0
    ImGuiContext& g = *GImGui;
14281
0
    ImGuiWindow* window = g.CurrentWindow;
14282
14283
0
    const char* prefix = g.LogNextPrefix;
14284
0
    const char* suffix = g.LogNextSuffix;
14285
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14286
14287
0
    if (!text_end)
14288
0
        text_end = FindRenderedTextEnd(text, text_end);
14289
14290
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14291
0
    if (ref_pos)
14292
0
        g.LogLinePosY = ref_pos->y;
14293
0
    if (log_new_line)
14294
0
    {
14295
0
        LogText(IM_NEWLINE);
14296
0
        g.LogLineFirstItem = true;
14297
0
    }
14298
14299
0
    if (prefix)
14300
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14301
14302
    // Re-adjust padding if we have popped out of our starting depth
14303
0
    if (g.LogDepthRef > window->DC.TreeDepth)
14304
0
        g.LogDepthRef = window->DC.TreeDepth;
14305
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14306
14307
0
    const char* text_remaining = text;
14308
0
    for (;;)
14309
0
    {
14310
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14311
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14312
0
        const char* line_start = text_remaining;
14313
0
        const char* line_end = ImStreolRange(line_start, text_end);
14314
0
        const bool is_last_line = (line_end == text_end);
14315
0
        if (line_start != line_end || !is_last_line)
14316
0
        {
14317
0
            const int line_length = (int)(line_end - line_start);
14318
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14319
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14320
0
            g.LogLineFirstItem = false;
14321
0
            if (*line_end == '\n')
14322
0
            {
14323
0
                LogText(IM_NEWLINE);
14324
0
                g.LogLineFirstItem = true;
14325
0
            }
14326
0
        }
14327
0
        if (is_last_line)
14328
0
            break;
14329
0
        text_remaining = line_end + 1;
14330
0
    }
14331
14332
0
    if (suffix)
14333
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14334
0
}
14335
14336
// Start logging/capturing text output
14337
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14338
0
{
14339
0
    ImGuiContext& g = *GImGui;
14340
0
    ImGuiWindow* window = g.CurrentWindow;
14341
0
    IM_ASSERT(g.LogEnabled == false);
14342
0
    IM_ASSERT(g.LogFile == NULL);
14343
0
    IM_ASSERT(g.LogBuffer.empty());
14344
0
    g.LogEnabled = g.ItemUnclipByLog = true;
14345
0
    g.LogType = type;
14346
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14347
0
    g.LogDepthRef = window->DC.TreeDepth;
14348
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14349
0
    g.LogLinePosY = FLT_MAX;
14350
0
    g.LogLineFirstItem = true;
14351
0
}
14352
14353
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14354
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14355
0
{
14356
0
    ImGuiContext& g = *GImGui;
14357
0
    g.LogNextPrefix = prefix;
14358
0
    g.LogNextSuffix = suffix;
14359
0
}
14360
14361
void ImGui::LogToTTY(int auto_open_depth)
14362
0
{
14363
0
    ImGuiContext& g = *GImGui;
14364
0
    if (g.LogEnabled)
14365
0
        return;
14366
0
    IM_UNUSED(auto_open_depth);
14367
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14368
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14369
0
    g.LogFile = stdout;
14370
0
#endif
14371
0
}
14372
14373
// Start logging/capturing text output to given file
14374
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14375
0
{
14376
0
    ImGuiContext& g = *GImGui;
14377
0
    if (g.LogEnabled)
14378
0
        return;
14379
14380
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14381
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14382
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14383
0
    if (!filename)
14384
0
        filename = g.IO.LogFilename;
14385
0
    if (!filename || !filename[0])
14386
0
        return;
14387
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14388
0
    if (!f)
14389
0
    {
14390
0
        IM_ASSERT(0);
14391
0
        return;
14392
0
    }
14393
14394
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14395
0
    g.LogFile = f;
14396
0
}
14397
14398
// Start logging/capturing text output to clipboard
14399
void ImGui::LogToClipboard(int auto_open_depth)
14400
0
{
14401
0
    ImGuiContext& g = *GImGui;
14402
0
    if (g.LogEnabled)
14403
0
        return;
14404
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14405
0
}
14406
14407
void ImGui::LogToBuffer(int auto_open_depth)
14408
0
{
14409
0
    ImGuiContext& g = *GImGui;
14410
0
    if (g.LogEnabled)
14411
0
        return;
14412
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14413
0
}
14414
14415
void ImGui::LogFinish()
14416
277k
{
14417
277k
    ImGuiContext& g = *GImGui;
14418
277k
    if (!g.LogEnabled)
14419
277k
        return;
14420
14421
0
    LogText(IM_NEWLINE);
14422
0
    switch (g.LogType)
14423
0
    {
14424
0
    case ImGuiLogType_TTY:
14425
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14426
0
        fflush(g.LogFile);
14427
0
#endif
14428
0
        break;
14429
0
    case ImGuiLogType_File:
14430
0
        ImFileClose(g.LogFile);
14431
0
        break;
14432
0
    case ImGuiLogType_Buffer:
14433
0
        break;
14434
0
    case ImGuiLogType_Clipboard:
14435
0
        if (!g.LogBuffer.empty())
14436
0
            SetClipboardText(g.LogBuffer.begin());
14437
0
        break;
14438
0
    case ImGuiLogType_None:
14439
0
        IM_ASSERT(0);
14440
0
        break;
14441
0
    }
14442
14443
0
    g.LogEnabled = g.ItemUnclipByLog = false;
14444
0
    g.LogType = ImGuiLogType_None;
14445
0
    g.LogFile = NULL;
14446
0
    g.LogBuffer.clear();
14447
0
}
14448
14449
// Helper to display logging buttons
14450
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14451
void ImGui::LogButtons()
14452
0
{
14453
0
    ImGuiContext& g = *GImGui;
14454
14455
0
    PushID("LogButtons");
14456
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14457
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14458
#else
14459
    const bool log_to_tty = false;
14460
#endif
14461
0
    const bool log_to_file = Button("Log To File"); SameLine();
14462
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14463
0
    PushTabStop(false);
14464
0
    SetNextItemWidth(80.0f);
14465
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14466
0
    PopTabStop();
14467
0
    PopID();
14468
14469
    // Start logging at the end of the function so that the buttons don't appear in the log
14470
0
    if (log_to_tty)
14471
0
        LogToTTY();
14472
0
    if (log_to_file)
14473
0
        LogToFile();
14474
0
    if (log_to_clipboard)
14475
0
        LogToClipboard();
14476
0
}
14477
14478
14479
//-----------------------------------------------------------------------------
14480
// [SECTION] SETTINGS
14481
//-----------------------------------------------------------------------------
14482
// - UpdateSettings() [Internal]
14483
// - MarkIniSettingsDirty() [Internal]
14484
// - FindSettingsHandler() [Internal]
14485
// - ClearIniSettings() [Internal]
14486
// - LoadIniSettingsFromDisk()
14487
// - LoadIniSettingsFromMemory()
14488
// - SaveIniSettingsToDisk()
14489
// - SaveIniSettingsToMemory()
14490
//-----------------------------------------------------------------------------
14491
// - CreateNewWindowSettings() [Internal]
14492
// - FindWindowSettingsByID() [Internal]
14493
// - FindWindowSettingsByWindow() [Internal]
14494
// - ClearWindowSettings() [Internal]
14495
// - WindowSettingsHandler_***() [Internal]
14496
//-----------------------------------------------------------------------------
14497
14498
// Called by NewFrame()
14499
void ImGui::UpdateSettings()
14500
138k
{
14501
    // Load settings on first frame (if not explicitly loaded manually before)
14502
138k
    ImGuiContext& g = *GImGui;
14503
138k
    if (!g.SettingsLoaded)
14504
1
    {
14505
1
        IM_ASSERT(g.SettingsWindows.empty());
14506
1
        if (g.IO.IniFilename)
14507
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14508
1
        g.SettingsLoaded = true;
14509
1
    }
14510
14511
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14512
138k
    if (g.SettingsDirtyTimer > 0.0f)
14513
2.70k
    {
14514
2.70k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14515
2.70k
        if (g.SettingsDirtyTimer <= 0.0f)
14516
9
        {
14517
9
            if (g.IO.IniFilename != NULL)
14518
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14519
9
            else
14520
9
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14521
9
            g.SettingsDirtyTimer = 0.0f;
14522
9
        }
14523
2.70k
    }
14524
138k
}
14525
14526
void ImGui::MarkIniSettingsDirty()
14527
0
{
14528
0
    ImGuiContext& g = *GImGui;
14529
0
    if (g.SettingsDirtyTimer <= 0.0f)
14530
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14531
0
}
14532
14533
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14534
22.7k
{
14535
22.7k
    ImGuiContext& g = *GImGui;
14536
22.7k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14537
14
        if (g.SettingsDirtyTimer <= 0.0f)
14538
9
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14539
22.7k
}
14540
14541
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14542
2
{
14543
2
    ImGuiContext& g = *GImGui;
14544
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14545
2
    g.SettingsHandlers.push_back(*handler);
14546
2
}
14547
14548
void ImGui::RemoveSettingsHandler(const char* type_name)
14549
0
{
14550
0
    ImGuiContext& g = *GImGui;
14551
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14552
0
        g.SettingsHandlers.erase(handler);
14553
0
}
14554
14555
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14556
2
{
14557
2
    ImGuiContext& g = *GImGui;
14558
2
    const ImGuiID type_hash = ImHashStr(type_name);
14559
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14560
1
        if (handler.TypeHash == type_hash)
14561
0
            return &handler;
14562
2
    return NULL;
14563
2
}
14564
14565
// Clear all settings (windows, tables, docking etc.)
14566
void ImGui::ClearIniSettings()
14567
0
{
14568
0
    ImGuiContext& g = *GImGui;
14569
0
    g.SettingsIniData.clear();
14570
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14571
0
        if (handler.ClearAllFn != NULL)
14572
0
            handler.ClearAllFn(&g, &handler);
14573
0
}
14574
14575
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14576
0
{
14577
0
    size_t file_data_size = 0;
14578
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14579
0
    if (!file_data)
14580
0
        return;
14581
0
    if (file_data_size > 0)
14582
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14583
0
    IM_FREE(file_data);
14584
0
}
14585
14586
// Zero-tolerance, no error reporting, cheap .ini parsing
14587
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14588
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14589
0
{
14590
0
    ImGuiContext& g = *GImGui;
14591
0
    IM_ASSERT(g.Initialized);
14592
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14593
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14594
14595
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14596
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14597
0
    if (ini_size == 0)
14598
0
        ini_size = strlen(ini_data);
14599
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14600
0
    char* const buf = g.SettingsIniData.Buf.Data;
14601
0
    char* const buf_end = buf + ini_size;
14602
0
    memcpy(buf, ini_data, ini_size);
14603
0
    buf_end[0] = 0;
14604
14605
    // Call pre-read handlers
14606
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14607
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14608
0
        if (handler.ReadInitFn != NULL)
14609
0
            handler.ReadInitFn(&g, &handler);
14610
14611
0
    void* entry_data = NULL;
14612
0
    ImGuiSettingsHandler* entry_handler = NULL;
14613
14614
0
    char* line_end = NULL;
14615
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14616
0
    {
14617
        // Skip new lines markers, then find end of the line
14618
0
        while (*line == '\n' || *line == '\r')
14619
0
            line++;
14620
0
        line_end = line;
14621
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14622
0
            line_end++;
14623
0
        line_end[0] = 0;
14624
0
        if (line[0] == ';')
14625
0
            continue;
14626
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14627
0
        {
14628
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14629
0
            line_end[-1] = 0;
14630
0
            const char* name_end = line_end - 1;
14631
0
            const char* type_start = line + 1;
14632
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14633
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14634
0
            if (!type_end || !name_start)
14635
0
                continue;
14636
0
            *type_end = 0; // Overwrite first ']'
14637
0
            name_start++;  // Skip second '['
14638
0
            entry_handler = FindSettingsHandler(type_start);
14639
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14640
0
        }
14641
0
        else if (entry_handler != NULL && entry_data != NULL)
14642
0
        {
14643
            // Let type handler parse the line
14644
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14645
0
        }
14646
0
    }
14647
0
    g.SettingsLoaded = true;
14648
14649
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14650
0
    memcpy(buf, ini_data, ini_size);
14651
14652
    // Call post-read handlers
14653
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14654
0
        if (handler.ApplyAllFn != NULL)
14655
0
            handler.ApplyAllFn(&g, &handler);
14656
0
}
14657
14658
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14659
0
{
14660
0
    ImGuiContext& g = *GImGui;
14661
0
    g.SettingsDirtyTimer = 0.0f;
14662
0
    if (!ini_filename)
14663
0
        return;
14664
14665
0
    size_t ini_data_size = 0;
14666
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14667
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14668
0
    if (!f)
14669
0
        return;
14670
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14671
0
    ImFileClose(f);
14672
0
}
14673
14674
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14675
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14676
0
{
14677
0
    ImGuiContext& g = *GImGui;
14678
0
    g.SettingsDirtyTimer = 0.0f;
14679
0
    g.SettingsIniData.Buf.resize(0);
14680
0
    g.SettingsIniData.Buf.push_back(0);
14681
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14682
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14683
0
    if (out_size)
14684
0
        *out_size = (size_t)g.SettingsIniData.size();
14685
0
    return g.SettingsIniData.c_str();
14686
0
}
14687
14688
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14689
0
{
14690
0
    ImGuiContext& g = *GImGui;
14691
14692
0
    if (g.IO.ConfigDebugIniSettings == false)
14693
0
    {
14694
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14695
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14696
0
        if (const char* p = strstr(name, "###"))
14697
0
            name = p;
14698
0
    }
14699
0
    const size_t name_len = strlen(name);
14700
14701
    // Allocate chunk
14702
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14703
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14704
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14705
0
    settings->ID = ImHashStr(name, name_len);
14706
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14707
14708
0
    return settings;
14709
0
}
14710
14711
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14712
// This is called once per window .ini entry + once per newly instantiated window.
14713
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14714
2
{
14715
2
    ImGuiContext& g = *GImGui;
14716
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14717
0
        if (settings->ID == id && !settings->WantDelete)
14718
0
            return settings;
14719
2
    return NULL;
14720
2
}
14721
14722
// This is faster if you are holding on a Window already as we don't need to perform a search.
14723
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14724
2
{
14725
2
    ImGuiContext& g = *GImGui;
14726
2
    if (window->SettingsOffset != -1)
14727
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14728
2
    return FindWindowSettingsByID(window->ID);
14729
2
}
14730
14731
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14732
void ImGui::ClearWindowSettings(const char* name)
14733
0
{
14734
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14735
0
    ImGuiContext& g = *GImGui;
14736
0
    ImGuiWindow* window = FindWindowByName(name);
14737
0
    if (window != NULL)
14738
0
    {
14739
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14740
0
        InitOrLoadWindowSettings(window, NULL);
14741
0
        if (window->DockId != 0)
14742
0
            DockContextProcessUndockWindow(&g, window, true);
14743
0
    }
14744
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14745
0
        settings->WantDelete = true;
14746
0
}
14747
14748
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14749
0
{
14750
0
    ImGuiContext& g = *ctx;
14751
0
    for (ImGuiWindow* window : g.Windows)
14752
0
        window->SettingsOffset = -1;
14753
0
    g.SettingsWindows.clear();
14754
0
}
14755
14756
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14757
0
{
14758
0
    ImGuiID id = ImHashStr(name);
14759
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14760
0
    if (settings)
14761
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14762
0
    else
14763
0
        settings = ImGui::CreateNewWindowSettings(name);
14764
0
    settings->ID = id;
14765
0
    settings->WantApply = true;
14766
0
    return (void*)settings;
14767
0
}
14768
14769
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14770
0
{
14771
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14772
0
    int x, y;
14773
0
    int i;
14774
0
    ImU32 u1;
14775
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14776
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14777
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14778
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14779
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14780
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14781
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14782
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14783
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14784
0
}
14785
14786
// Apply to existing windows (if any)
14787
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14788
0
{
14789
0
    ImGuiContext& g = *ctx;
14790
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14791
0
        if (settings->WantApply)
14792
0
        {
14793
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14794
0
                ApplyWindowSettings(window, settings);
14795
0
            settings->WantApply = false;
14796
0
        }
14797
0
}
14798
14799
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14800
0
{
14801
    // Gather data from windows that were active during this session
14802
    // (if a window wasn't opened in this session we preserve its settings)
14803
0
    ImGuiContext& g = *ctx;
14804
0
    for (ImGuiWindow* window : g.Windows)
14805
0
    {
14806
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14807
0
            continue;
14808
14809
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14810
0
        if (!settings)
14811
0
        {
14812
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14813
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14814
0
        }
14815
0
        IM_ASSERT(settings->ID == window->ID);
14816
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14817
0
        settings->Size = ImVec2ih(window->SizeFull);
14818
0
        settings->ViewportId = window->ViewportId;
14819
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14820
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14821
0
        settings->DockId = window->DockId;
14822
0
        settings->ClassId = window->WindowClass.ClassId;
14823
0
        settings->DockOrder = window->DockOrder;
14824
0
        settings->Collapsed = window->Collapsed;
14825
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14826
0
        settings->WantDelete = false;
14827
0
    }
14828
14829
    // Write to text buffer
14830
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14831
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14832
0
    {
14833
0
        if (settings->WantDelete)
14834
0
            continue;
14835
0
        const char* settings_name = settings->GetName();
14836
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14837
0
        if (settings->IsChild)
14838
0
        {
14839
0
            buf->appendf("IsChild=1\n");
14840
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14841
0
        }
14842
0
        else
14843
0
        {
14844
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14845
0
            {
14846
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14847
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14848
0
            }
14849
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14850
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14851
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14852
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14853
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14854
0
            if (settings->DockId != 0)
14855
0
            {
14856
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14857
0
                if (settings->DockOrder == -1)
14858
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14859
0
                else
14860
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14861
0
                if (settings->ClassId != 0)
14862
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14863
0
            }
14864
0
        }
14865
0
        buf->append("\n");
14866
0
    }
14867
0
}
14868
14869
14870
//-----------------------------------------------------------------------------
14871
// [SECTION] LOCALIZATION
14872
//-----------------------------------------------------------------------------
14873
14874
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14875
1
{
14876
1
    ImGuiContext& g = *GImGui;
14877
12
    for (int n = 0; n < count; n++)
14878
11
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14879
1
}
14880
14881
14882
//-----------------------------------------------------------------------------
14883
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14884
//-----------------------------------------------------------------------------
14885
// - GetMainViewport()
14886
// - FindViewportByID()
14887
// - FindViewportByPlatformHandle()
14888
// - SetCurrentViewport() [Internal]
14889
// - SetWindowViewport() [Internal]
14890
// - GetWindowAlwaysWantOwnViewport() [Internal]
14891
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14892
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14893
// - TranslateWindowsInViewport() [Internal]
14894
// - ScaleWindowsInViewport() [Internal]
14895
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14896
// - UpdateViewportsNewFrame() [Internal]
14897
// - UpdateViewportsEndFrame() [Internal]
14898
// - AddUpdateViewport() [Internal]
14899
// - WindowSelectViewport() [Internal]
14900
// - WindowSyncOwnedViewport() [Internal]
14901
// - UpdatePlatformWindows()
14902
// - RenderPlatformWindowsDefault()
14903
// - FindPlatformMonitorForPos() [Internal]
14904
// - FindPlatformMonitorForRect() [Internal]
14905
// - UpdateViewportPlatformMonitor() [Internal]
14906
// - DestroyPlatformWindow() [Internal]
14907
// - DestroyPlatformWindows()
14908
//-----------------------------------------------------------------------------
14909
14910
ImGuiViewport* ImGui::GetMainViewport()
14911
578k
{
14912
578k
    ImGuiContext& g = *GImGui;
14913
578k
    return g.Viewports[0];
14914
578k
}
14915
14916
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14917
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14918
138k
{
14919
138k
    ImGuiContext& g = *GImGui;
14920
138k
    for (ImGuiViewportP* viewport : g.Viewports)
14921
138k
        if (viewport->ID == id)
14922
138k
            return viewport;
14923
0
    return NULL;
14924
138k
}
14925
14926
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14927
0
{
14928
0
    ImGuiContext& g = *GImGui;
14929
0
    for (ImGuiViewportP* viewport : g.Viewports)
14930
0
        if (viewport->PlatformHandle == platform_handle)
14931
0
            return viewport;
14932
0
    return NULL;
14933
0
}
14934
14935
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14936
601k
{
14937
601k
    ImGuiContext& g = *GImGui;
14938
601k
    (void)current_window;
14939
14940
601k
    if (viewport)
14941
462k
        viewport->LastFrameActive = g.FrameCount;
14942
601k
    if (g.CurrentViewport == viewport)
14943
323k
        return;
14944
277k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14945
277k
    g.CurrentViewport = viewport;
14946
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14947
14948
    // Notify platform layer of viewport changes
14949
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14950
277k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14951
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14952
277k
}
14953
14954
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14955
300k
{
14956
    // Abandon viewport
14957
300k
    if (window->ViewportOwned && window->Viewport->Window == window)
14958
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14959
14960
300k
    window->Viewport = viewport;
14961
300k
    window->ViewportId = viewport->ID;
14962
300k
    window->ViewportOwned = (viewport->Window == window);
14963
300k
}
14964
14965
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14966
0
{
14967
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14968
0
    ImGuiContext& g = *GImGui;
14969
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14970
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14971
0
            if (!window->DockIsActive)
14972
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14973
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14974
0
                        return true;
14975
0
    return false;
14976
0
}
14977
14978
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14979
0
{
14980
0
    ImGuiContext& g = *GImGui;
14981
0
    if (window->Viewport == viewport)
14982
0
        return false;
14983
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14984
0
        return false;
14985
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14986
0
        return false;
14987
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14988
0
        return false;
14989
0
    if (GetWindowAlwaysWantOwnViewport(window))
14990
0
        return false;
14991
14992
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14993
0
    for (ImGuiWindow* window_behind : g.Windows)
14994
0
    {
14995
0
        if (window_behind == window)
14996
0
            break;
14997
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14998
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14999
0
                return false;
15000
0
    }
15001
15002
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
15003
0
    ImGuiViewportP* old_viewport = window->Viewport;
15004
0
    if (window->ViewportOwned)
15005
0
        for (int n = 0; n < g.Windows.Size; n++)
15006
0
            if (g.Windows[n]->Viewport == old_viewport)
15007
0
                SetWindowViewport(g.Windows[n], viewport);
15008
0
    SetWindowViewport(window, viewport);
15009
0
    BringWindowToDisplayFront(window);
15010
15011
0
    return true;
15012
0
}
15013
15014
// FIXME: handle 0 to N host viewports
15015
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
15016
0
{
15017
0
    ImGuiContext& g = *GImGui;
15018
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
15019
0
}
15020
15021
// Translate Dear ImGui windows when a Host Viewport has been moved
15022
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15023
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
15024
0
{
15025
0
    ImGuiContext& g = *GImGui;
15026
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
15027
15028
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
15029
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
15030
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
15031
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
15032
    // and so the window will appear to teleport when releasing the mouse.
15033
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
15034
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
15035
0
    ImVec2 delta_pos = new_pos - old_pos;
15036
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
15037
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
15038
0
            TranslateWindow(window, delta_pos);
15039
0
}
15040
15041
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
15042
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
15043
0
{
15044
0
    ImGuiContext& g = *GImGui;
15045
0
    if (viewport->Window)
15046
0
    {
15047
0
        ScaleWindow(viewport->Window, scale);
15048
0
    }
15049
0
    else
15050
0
    {
15051
0
        for (ImGuiWindow* window : g.Windows)
15052
0
            if (window->Viewport == viewport)
15053
0
                ScaleWindow(window, scale);
15054
0
    }
15055
0
}
15056
15057
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
15058
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15059
// B) It requires Platform_GetWindowFocus to be implemented by backend.
15060
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
15061
0
{
15062
0
    ImGuiContext& g = *GImGui;
15063
0
    ImGuiViewportP* best_candidate = NULL;
15064
0
    for (ImGuiViewportP* viewport : g.Viewports)
15065
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
15066
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
15067
0
                best_candidate = viewport;
15068
0
    return best_candidate;
15069
0
}
15070
15071
// Update viewports and monitor infos
15072
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
15073
static void ImGui::UpdateViewportsNewFrame()
15074
138k
{
15075
138k
    ImGuiContext& g = *GImGui;
15076
138k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
15077
15078
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
15079
    // Update Focused status
15080
138k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
15081
138k
    if (viewports_enabled)
15082
0
    {
15083
0
        ImGuiViewportP* focused_viewport = NULL;
15084
0
        for (ImGuiViewportP* viewport : g.Viewports)
15085
0
        {
15086
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
15087
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
15088
0
            {
15089
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
15090
0
                if (is_minimized)
15091
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
15092
0
                else
15093
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
15094
0
            }
15095
15096
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
15097
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
15098
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
15099
0
            {
15100
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
15101
0
                if (is_focused)
15102
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
15103
0
                else
15104
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
15105
0
                if (is_focused)
15106
0
                    focused_viewport = viewport;
15107
0
            }
15108
0
        }
15109
15110
        // Focused viewport has changed?
15111
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
15112
0
        {
15113
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
15114
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
15115
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
15116
15117
            // Store a tag so we can infer z-order easily from all our windows
15118
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
15119
            // will keep the front most stamp instead of losing it back to their parent viewport.
15120
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15121
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15122
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
15123
15124
            // Focus associated dear imgui window
15125
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
15126
            // - if focus didn't happen because we destroyed another window (#6462)
15127
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
15128
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
15129
0
            if (apply_imgui_focus_on_focused_viewport)
15130
0
            {
15131
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
15132
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
15133
0
                if (focused_viewport->Window != NULL)
15134
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
15135
0
                else if (focused_viewport->LastFocusedHadNavWindow)
15136
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
15137
0
                else
15138
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
15139
0
            }
15140
0
        }
15141
0
        if (focused_viewport)
15142
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
15143
0
    }
15144
15145
    // Create/update main viewport with current platform position.
15146
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
15147
138k
    ImGuiViewportP* main_viewport = g.Viewports[0];
15148
138k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
15149
138k
    IM_ASSERT(main_viewport->Window == NULL);
15150
138k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
15151
138k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
15152
138k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
15153
0
    {
15154
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
15155
0
        main_viewport_size = main_viewport->Size;
15156
0
    }
15157
138k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
15158
15159
138k
    g.CurrentDpiScale = 0.0f;
15160
138k
    g.CurrentViewport = NULL;
15161
138k
    g.MouseViewport = NULL;
15162
277k
    for (int n = 0; n < g.Viewports.Size; n++)
15163
138k
    {
15164
138k
        ImGuiViewportP* viewport = g.Viewports[n];
15165
138k
        viewport->Idx = n;
15166
15167
        // Erase unused viewports
15168
138k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
15169
0
        {
15170
0
            DestroyViewport(viewport);
15171
0
            n--;
15172
0
            continue;
15173
0
        }
15174
15175
138k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
15176
138k
        if (viewports_enabled)
15177
0
        {
15178
            // Update Position and Size (from Platform Window to ImGui) if requested.
15179
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
15180
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
15181
0
            {
15182
                // Viewport->WorkPos and WorkSize will be updated below
15183
0
                if (viewport->PlatformRequestMove)
15184
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
15185
0
                if (viewport->PlatformRequestResize)
15186
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
15187
0
            }
15188
0
        }
15189
15190
        // Update/copy monitor info
15191
138k
        UpdateViewportPlatformMonitor(viewport);
15192
15193
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
15194
138k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
15195
138k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
15196
138k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
15197
138k
        viewport->UpdateWorkRect();
15198
15199
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
15200
138k
        viewport->Alpha = 1.0f;
15201
15202
        // Translate Dear ImGui windows when a Host Viewport has been moved
15203
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15204
138k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
15205
138k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
15206
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
15207
15208
        // Update DPI scale
15209
138k
        float new_dpi_scale;
15210
138k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
15211
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
15212
138k
        else if (viewport->PlatformMonitor != -1)
15213
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15214
138k
        else
15215
138k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
15216
138k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
15217
0
        {
15218
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
15219
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
15220
0
                ScaleWindowsInViewport(viewport, scale_factor);
15221
            //if (viewport == GetMainViewport())
15222
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
15223
15224
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
15225
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
15226
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
15227
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
15228
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
15229
0
        }
15230
138k
        viewport->DpiScale = new_dpi_scale;
15231
138k
    }
15232
15233
    // Update fallback monitor
15234
138k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
15235
138k
    if (g.PlatformIO.Monitors.Size == 0)
15236
138k
    {
15237
138k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
15238
138k
        monitor->MainPos = main_viewport->Pos;
15239
138k
        monitor->MainSize = main_viewport->Size;
15240
138k
        monitor->WorkPos = main_viewport->WorkPos;
15241
138k
        monitor->WorkSize = main_viewport->WorkSize;
15242
138k
        monitor->DpiScale = main_viewport->DpiScale;
15243
138k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
15244
138k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
15245
138k
    }
15246
138k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
15247
0
    {
15248
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
15249
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
15250
0
    }
15251
15252
138k
    if (!viewports_enabled)
15253
138k
    {
15254
138k
        g.MouseViewport = main_viewport;
15255
138k
        return;
15256
138k
    }
15257
15258
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
15259
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
15260
0
    ImGuiViewportP* viewport_hovered = NULL;
15261
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
15262
0
    {
15263
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
15264
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15265
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
15266
0
    }
15267
0
    else
15268
0
    {
15269
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
15270
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15271
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
15272
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
15273
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
15274
0
    }
15275
0
    if (viewport_hovered != NULL)
15276
0
        g.MouseLastHoveredViewport = viewport_hovered;
15277
0
    else if (g.MouseLastHoveredViewport == NULL)
15278
0
        g.MouseLastHoveredViewport = g.Viewports[0];
15279
15280
    // Update mouse reference viewport
15281
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
15282
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
15283
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
15284
0
        g.MouseViewport = g.MovingWindow->Viewport;
15285
0
    else
15286
0
        g.MouseViewport = g.MouseLastHoveredViewport;
15287
15288
    // When dragging something, always refer to the last hovered viewport.
15289
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
15290
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
15291
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
15292
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
15293
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
15294
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
15295
0
        viewport_hovered = g.MouseLastHoveredViewport;
15296
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
15297
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15298
0
            g.MouseViewport = viewport_hovered;
15299
15300
0
    IM_ASSERT(g.MouseViewport != NULL);
15301
0
}
15302
15303
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
15304
static void ImGui::UpdateViewportsEndFrame()
15305
138k
{
15306
138k
    ImGuiContext& g = *GImGui;
15307
138k
    g.PlatformIO.Viewports.resize(0);
15308
277k
    for (int i = 0; i < g.Viewports.Size; i++)
15309
138k
    {
15310
138k
        ImGuiViewportP* viewport = g.Viewports[i];
15311
138k
        viewport->LastPos = viewport->Pos;
15312
138k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
15313
0
            if (i > 0) // Always include main viewport in the list
15314
0
                continue;
15315
138k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15316
0
            continue;
15317
138k
        if (i > 0)
15318
138k
            IM_ASSERT(viewport->Window != NULL);
15319
138k
        g.PlatformIO.Viewports.push_back(viewport);
15320
138k
    }
15321
138k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15322
138k
}
15323
15324
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15325
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15326
138k
{
15327
138k
    ImGuiContext& g = *GImGui;
15328
138k
    IM_ASSERT(id != 0);
15329
15330
138k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15331
138k
    if (window != NULL)
15332
0
    {
15333
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15334
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15335
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15336
0
            flags |= ImGuiViewportFlags_NoInputs;
15337
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15338
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15339
0
    }
15340
15341
138k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15342
138k
    if (viewport)
15343
138k
    {
15344
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15345
138k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15346
138k
            viewport->Pos = pos;
15347
138k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15348
138k
            viewport->Size = size;
15349
138k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15350
138k
    }
15351
0
    else
15352
0
    {
15353
        // New viewport
15354
0
        viewport = IM_NEW(ImGuiViewportP)();
15355
0
        viewport->ID = id;
15356
0
        viewport->Idx = g.Viewports.Size;
15357
0
        viewport->Pos = viewport->LastPos = pos;
15358
0
        viewport->Size = size;
15359
0
        viewport->Flags = flags;
15360
0
        UpdateViewportPlatformMonitor(viewport);
15361
0
        g.Viewports.push_back(viewport);
15362
0
        g.ViewportCreatedCount++;
15363
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15364
15365
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15366
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15367
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15368
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15369
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15370
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15371
15372
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15373
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15374
0
        if (viewport->PlatformMonitor != -1)
15375
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15376
0
    }
15377
15378
138k
    viewport->Window = window;
15379
138k
    viewport->LastFrameActive = g.FrameCount;
15380
138k
    viewport->UpdateWorkRect();
15381
138k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15382
15383
138k
    if (window != NULL)
15384
0
        window->ViewportOwned = true;
15385
15386
138k
    return viewport;
15387
138k
}
15388
15389
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15390
0
{
15391
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15392
0
    ImGuiContext& g = *GImGui;
15393
0
    for (ImGuiWindow* window : g.Windows)
15394
0
    {
15395
0
        if (window->Viewport != viewport)
15396
0
            continue;
15397
0
        window->Viewport = NULL;
15398
0
        window->ViewportOwned = false;
15399
0
    }
15400
0
    if (viewport == g.MouseLastHoveredViewport)
15401
0
        g.MouseLastHoveredViewport = NULL;
15402
15403
    // Destroy
15404
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15405
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15406
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15407
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15408
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15409
0
    IM_DELETE(viewport);
15410
0
}
15411
15412
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15413
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15414
300k
{
15415
300k
    ImGuiContext& g = *GImGui;
15416
300k
    ImGuiWindowFlags flags = window->Flags;
15417
300k
    window->ViewportAllowPlatformMonitorExtend = -1;
15418
15419
    // Restore main viewport if multi-viewport is not supported by the backend
15420
300k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15421
300k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15422
300k
    {
15423
300k
        SetWindowViewport(window, main_viewport);
15424
300k
        return;
15425
300k
    }
15426
0
    window->ViewportOwned = false;
15427
15428
    // Appearing popups reset their viewport so they can inherit again
15429
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15430
0
    {
15431
0
        window->Viewport = NULL;
15432
0
        window->ViewportId = 0;
15433
0
    }
15434
15435
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15436
0
    {
15437
        // By default inherit from parent window
15438
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15439
0
            window->Viewport = window->ParentWindow->Viewport;
15440
15441
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15442
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15443
0
        {
15444
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15445
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15446
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15447
0
        }
15448
0
    }
15449
15450
0
    bool lock_viewport = false;
15451
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15452
0
    {
15453
        // Code explicitly request a viewport
15454
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15455
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15456
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15457
0
        {
15458
0
            window->Viewport->Window = window;
15459
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15460
0
        }
15461
0
        lock_viewport = true;
15462
0
    }
15463
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15464
0
    {
15465
        // Always inherit viewport from parent window
15466
0
        if (window->DockNode && window->DockNode->HostWindow)
15467
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15468
0
        window->Viewport = window->ParentWindow->Viewport;
15469
0
    }
15470
0
    else if (window->DockNode && window->DockNode->HostWindow)
15471
0
    {
15472
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15473
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15474
0
    }
15475
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15476
0
    {
15477
0
        window->Viewport = g.MouseViewport;
15478
0
    }
15479
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15480
0
    {
15481
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15482
0
    }
15483
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15484
0
    {
15485
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15486
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15487
0
    }
15488
0
    else
15489
0
    {
15490
        // Merge into host viewport?
15491
        // We cannot test window->ViewportOwned as it set lower in the function.
15492
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15493
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15494
0
        if (try_to_merge_into_host_viewport)
15495
0
            UpdateTryMergeWindowIntoHostViewports(window);
15496
0
    }
15497
15498
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15499
0
    if (window->Viewport == NULL)
15500
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15501
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15502
15503
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15504
0
    if (!lock_viewport)
15505
0
    {
15506
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15507
0
        {
15508
            // We need to take account of the possibility that mouse may become invalid.
15509
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15510
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15511
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15512
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15513
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15514
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15515
0
            else
15516
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15517
0
        }
15518
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15519
0
        {
15520
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15521
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15522
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15523
0
            {
15524
                // Steal/transfer ownership
15525
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15526
0
                window->Viewport->Window = window;
15527
0
                window->Viewport->ID = window->ID;
15528
0
                window->Viewport->LastNameHash = 0;
15529
0
            }
15530
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15531
0
            {
15532
                // New viewport
15533
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15534
0
            }
15535
0
        }
15536
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15537
0
        {
15538
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15539
            // Child windows are kept contained within their parent.
15540
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15541
0
        }
15542
0
    }
15543
15544
    // Update flags
15545
0
    window->ViewportOwned = (window == window->Viewport->Window);
15546
0
    window->ViewportId = window->Viewport->ID;
15547
15548
    // If the OS window has a title bar, hide our imgui title bar
15549
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15550
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15551
0
}
15552
15553
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15554
0
{
15555
0
    ImGuiContext& g = *GImGui;
15556
15557
0
    bool viewport_rect_changed = false;
15558
15559
    // Synchronize window --> viewport in most situations
15560
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15561
0
    if (window->Viewport->PlatformRequestMove)
15562
0
    {
15563
0
        window->Pos = window->Viewport->Pos;
15564
0
        MarkIniSettingsDirty(window);
15565
0
    }
15566
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15567
0
    {
15568
0
        viewport_rect_changed = true;
15569
0
        window->Viewport->Pos = window->Pos;
15570
0
    }
15571
15572
0
    if (window->Viewport->PlatformRequestResize)
15573
0
    {
15574
0
        window->Size = window->SizeFull = window->Viewport->Size;
15575
0
        MarkIniSettingsDirty(window);
15576
0
    }
15577
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15578
0
    {
15579
0
        viewport_rect_changed = true;
15580
0
        window->Viewport->Size = window->Size;
15581
0
    }
15582
0
    window->Viewport->UpdateWorkRect();
15583
15584
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15585
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15586
0
    if (viewport_rect_changed)
15587
0
        UpdateViewportPlatformMonitor(window->Viewport);
15588
15589
    // Update common viewport flags
15590
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15591
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15592
0
    ImGuiWindowFlags window_flags = window->Flags;
15593
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15594
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15595
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15596
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15597
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15598
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15599
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15600
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15601
15602
    // Not correct to set modal as topmost because:
15603
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15604
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15605
    //if (flags & ImGuiWindowFlags_Modal)
15606
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15607
15608
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15609
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15610
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15611
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15612
0
    if (is_short_lived_floating_window && !is_modal)
15613
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15614
15615
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15616
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15617
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15618
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15619
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15620
15621
    // We can also tell the backend that clearing the platform window won't be necessary,
15622
    // as our window background is filling the viewport and we have disabled BgAlpha.
15623
    // FIXME: Work on support for per-viewport transparency (#2766)
15624
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15625
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15626
15627
0
    window->Viewport->Flags = viewport_flags;
15628
15629
    // Update parent viewport ID
15630
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15631
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15632
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15633
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15634
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15635
0
    else
15636
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15637
0
}
15638
15639
// Called by user at the end of the main loop, after EndFrame()
15640
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15641
void ImGui::UpdatePlatformWindows()
15642
0
{
15643
0
    ImGuiContext& g = *GImGui;
15644
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15645
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15646
0
    g.FrameCountPlatformEnded = g.FrameCount;
15647
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15648
0
        return;
15649
15650
    // Create/resize/destroy platform windows to match each active viewport.
15651
    // Skip the main viewport (index 0), which is always fully handled by the application!
15652
0
    for (int i = 1; i < g.Viewports.Size; i++)
15653
0
    {
15654
0
        ImGuiViewportP* viewport = g.Viewports[i];
15655
15656
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15657
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15658
0
        bool destroy_platform_window = false;
15659
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15660
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15661
0
        if (destroy_platform_window)
15662
0
        {
15663
0
            DestroyPlatformWindow(viewport);
15664
0
            continue;
15665
0
        }
15666
15667
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15668
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15669
0
            continue;
15670
15671
        // Create window
15672
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15673
0
        if (is_new_platform_window)
15674
0
        {
15675
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15676
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15677
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15678
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15679
0
            g.PlatformWindowsCreatedCount++;
15680
0
            viewport->LastNameHash = 0;
15681
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15682
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15683
0
            viewport->PlatformWindowCreated = true;
15684
0
        }
15685
15686
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15687
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15688
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15689
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15690
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15691
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15692
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15693
0
        viewport->LastPlatformPos = viewport->Pos;
15694
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15695
15696
        // Update title bar (if it changed)
15697
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15698
0
        {
15699
0
            const char* title_begin = window_for_title->Name;
15700
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15701
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15702
0
            if (viewport->LastNameHash != title_hash)
15703
0
            {
15704
0
                char title_end_backup_c = *title_end;
15705
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15706
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15707
0
                *title_end = title_end_backup_c;
15708
0
                viewport->LastNameHash = title_hash;
15709
0
            }
15710
0
        }
15711
15712
        // Update alpha (if it changed)
15713
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15714
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15715
0
        viewport->LastAlpha = viewport->Alpha;
15716
15717
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15718
0
        if (g.PlatformIO.Platform_UpdateWindow)
15719
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15720
15721
0
        if (is_new_platform_window)
15722
0
        {
15723
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15724
0
            if (g.FrameCount < 3)
15725
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15726
15727
            // Show window
15728
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15729
15730
            // Even without focus, we assume the window becomes front-most.
15731
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15732
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15733
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15734
0
        }
15735
15736
        // Clear request flags
15737
0
        viewport->ClearRequestFlags();
15738
0
    }
15739
0
}
15740
15741
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15742
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15743
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15744
//
15745
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15746
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15747
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15748
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15749
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15750
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15751
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15752
//
15753
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15754
0
{
15755
    // Skip the main viewport (index 0), which is always fully handled by the application!
15756
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15757
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15758
0
    {
15759
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15760
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15761
0
            continue;
15762
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15763
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15764
0
    }
15765
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15766
0
    {
15767
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15768
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15769
0
            continue;
15770
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15771
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15772
0
    }
15773
0
}
15774
15775
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15776
0
{
15777
0
    ImGuiContext& g = *GImGui;
15778
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15779
0
    {
15780
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15781
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15782
0
            return monitor_n;
15783
0
    }
15784
0
    return -1;
15785
0
}
15786
15787
// Search for the monitor with the largest intersection area with the given rectangle
15788
// We generally try to avoid searching loops but the monitor count should be very small here
15789
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15790
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15791
138k
{
15792
138k
    ImGuiContext& g = *GImGui;
15793
15794
138k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15795
138k
    if (monitor_count <= 1)
15796
138k
        return monitor_count - 1;
15797
15798
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15799
    // This is necessary for tooltips which always resize down to zero at first.
15800
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15801
0
    int best_monitor_n = -1;
15802
0
    float best_monitor_surface = 0.001f;
15803
15804
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15805
0
    {
15806
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15807
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15808
0
        if (monitor_rect.Contains(rect))
15809
0
            return monitor_n;
15810
0
        ImRect overlapping_rect = rect;
15811
0
        overlapping_rect.ClipWithFull(monitor_rect);
15812
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15813
0
        if (overlapping_surface < best_monitor_surface)
15814
0
            continue;
15815
0
        best_monitor_surface = overlapping_surface;
15816
0
        best_monitor_n = monitor_n;
15817
0
    }
15818
0
    return best_monitor_n;
15819
0
}
15820
15821
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15822
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15823
138k
{
15824
138k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15825
138k
}
15826
15827
// Return value is always != NULL, but don't hold on it across frames.
15828
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15829
0
{
15830
0
    ImGuiContext& g = *GImGui;
15831
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15832
0
    int monitor_idx = viewport->PlatformMonitor;
15833
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15834
0
        return &g.PlatformIO.Monitors[monitor_idx];
15835
0
    return &g.FallbackMonitor;
15836
0
}
15837
15838
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15839
0
{
15840
0
    ImGuiContext& g = *GImGui;
15841
0
    if (viewport->PlatformWindowCreated)
15842
0
    {
15843
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15844
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15845
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15846
0
        if (g.PlatformIO.Platform_DestroyWindow)
15847
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15848
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15849
15850
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15851
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15852
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15853
0
            viewport->PlatformWindowCreated = false;
15854
0
    }
15855
0
    else
15856
0
    {
15857
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15858
0
    }
15859
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15860
0
    viewport->ClearRequestFlags();
15861
0
}
15862
15863
void ImGui::DestroyPlatformWindows()
15864
0
{
15865
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15866
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15867
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15868
    // code to operator a consistent manner.
15869
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15870
    // crashing if it doesn't have data stored.
15871
0
    ImGuiContext& g = *GImGui;
15872
0
    for (ImGuiViewportP* viewport : g.Viewports)
15873
0
        DestroyPlatformWindow(viewport);
15874
0
}
15875
15876
15877
//-----------------------------------------------------------------------------
15878
// [SECTION] DOCKING
15879
//-----------------------------------------------------------------------------
15880
// Docking: Internal Types
15881
// Docking: Forward Declarations
15882
// Docking: ImGuiDockContext
15883
// Docking: ImGuiDockContext Docking/Undocking functions
15884
// Docking: ImGuiDockNode
15885
// Docking: ImGuiDockNode Tree manipulation functions
15886
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15887
// Docking: Builder Functions
15888
// Docking: Begin/End Support Functions (called from Begin/End)
15889
// Docking: Settings
15890
//-----------------------------------------------------------------------------
15891
15892
//-----------------------------------------------------------------------------
15893
// Typical Docking call flow: (root level is generally public API):
15894
//-----------------------------------------------------------------------------
15895
// - NewFrame()                               new dear imgui frame
15896
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15897
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15898
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15899
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15900
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15901
//    | - DockContextProcessDock()            - process one docking request
15902
//    | - DockNodeUpdate()
15903
//    |   - DockNodeUpdateForRootNode()
15904
//    |     - DockNodeUpdateFlagsAndCollapse()
15905
//    |     - DockNodeFindInfo()
15906
//    |   - destroy unused node or tab bar
15907
//    |   - create dock node host window
15908
//    |      - Begin() etc.
15909
//    |   - DockNodeStartMouseMovingWindow()
15910
//    |   - DockNodeTreeUpdatePosSize()
15911
//    |   - DockNodeTreeUpdateSplitter()
15912
//    |   - draw node background
15913
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15914
//    |     - DockNodeAddTabBar()
15915
//    |     - DockNodeWindowMenuUpdate()
15916
//    |     - DockNodeCalcTabBarLayout()
15917
//    |     - BeginTabBarEx()
15918
//    |     - TabItemEx() calls
15919
//    |     - EndTabBar()
15920
//    |   - BeginDockableDragDropTarget()
15921
//    |      - DockNodeUpdate()               - recurse into child nodes...
15922
//-----------------------------------------------------------------------------
15923
// - DockSpace()                              user submit a dockspace into a window
15924
//    | Begin(Child)                          - create a child window
15925
//    | DockNodeUpdate()                      - call main dock node update function
15926
//    | End(Child)
15927
//    | ItemSize()
15928
//-----------------------------------------------------------------------------
15929
// - Begin()
15930
//    | BeginDocked()
15931
//    | BeginDockableDragDropSource()
15932
//    | BeginDockableDragDropTarget()
15933
//    | - DockNodePreviewDockRender()
15934
//-----------------------------------------------------------------------------
15935
// - EndFrame()
15936
//    | DockContextEndFrame()
15937
//-----------------------------------------------------------------------------
15938
15939
//-----------------------------------------------------------------------------
15940
// Docking: Internal Types
15941
//-----------------------------------------------------------------------------
15942
// - ImGuiDockRequestType
15943
// - ImGuiDockRequest
15944
// - ImGuiDockPreviewData
15945
// - ImGuiDockNodeSettings
15946
// - ImGuiDockContext
15947
//-----------------------------------------------------------------------------
15948
15949
enum ImGuiDockRequestType
15950
{
15951
    ImGuiDockRequestType_None = 0,
15952
    ImGuiDockRequestType_Dock,
15953
    ImGuiDockRequestType_Undock,
15954
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15955
};
15956
15957
struct ImGuiDockRequest
15958
{
15959
    ImGuiDockRequestType    Type;
15960
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15961
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15962
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15963
    ImGuiDir                DockSplitDir;
15964
    float                   DockSplitRatio;
15965
    bool                    DockSplitOuter;
15966
    ImGuiWindow*            UndockTargetWindow;
15967
    ImGuiDockNode*          UndockTargetNode;
15968
15969
    ImGuiDockRequest()
15970
0
    {
15971
0
        Type = ImGuiDockRequestType_None;
15972
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15973
0
        DockTargetNode = UndockTargetNode = NULL;
15974
0
        DockSplitDir = ImGuiDir_None;
15975
0
        DockSplitRatio = 0.5f;
15976
0
        DockSplitOuter = false;
15977
0
    }
15978
};
15979
15980
struct ImGuiDockPreviewData
15981
{
15982
    ImGuiDockNode   FutureNode;
15983
    bool            IsDropAllowed;
15984
    bool            IsCenterAvailable;
15985
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15986
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15987
    ImGuiDockNode*  SplitNode;
15988
    ImGuiDir        SplitDir;
15989
    float           SplitRatio;
15990
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15991
15992
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15993
};
15994
15995
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15996
struct ImGuiDockNodeSettings
15997
{
15998
    ImGuiID             ID;
15999
    ImGuiID             ParentNodeId;
16000
    ImGuiID             ParentWindowId;
16001
    ImGuiID             SelectedTabId;
16002
    signed char         SplitAxis;
16003
    char                Depth;
16004
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
16005
    ImVec2ih            Pos;
16006
    ImVec2ih            Size;
16007
    ImVec2ih            SizeRef;
16008
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
16009
};
16010
16011
//-----------------------------------------------------------------------------
16012
// Docking: Forward Declarations
16013
//-----------------------------------------------------------------------------
16014
16015
namespace ImGui
16016
{
16017
    // ImGuiDockContext
16018
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
16019
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
16020
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
16021
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
16022
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
16023
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
16024
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
16025
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
16026
16027
    // ImGuiDockNode
16028
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
16029
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16030
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16031
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
16032
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
16033
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
16034
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
16035
    static void             DockNodeUpdate(ImGuiDockNode* node);
16036
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
16037
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
16038
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
16039
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
16040
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
16041
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
16042
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
16043
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
16044
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
16045
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
16046
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
16047
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
16048
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
16049
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
16050
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
16051
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
16052
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
16053
16054
    // ImGuiDockNode tree manipulations
16055
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
16056
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
16057
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
16058
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
16059
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
16060
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
16061
16062
    // Settings
16063
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
16064
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
16065
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
16066
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
16067
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
16068
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
16069
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
16070
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
16071
}
16072
16073
//-----------------------------------------------------------------------------
16074
// Docking: ImGuiDockContext
16075
//-----------------------------------------------------------------------------
16076
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
16077
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
16078
// At boot time only, we run a simple GC to remove nodes that have no references.
16079
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
16080
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
16081
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
16082
//-----------------------------------------------------------------------------
16083
// - DockContextInitialize()
16084
// - DockContextShutdown()
16085
// - DockContextClearNodes()
16086
// - DockContextRebuildNodes()
16087
// - DockContextNewFrameUpdateUndocking()
16088
// - DockContextNewFrameUpdateDocking()
16089
// - DockContextEndFrame()
16090
// - DockContextFindNodeByID()
16091
// - DockContextBindNodeToWindow()
16092
// - DockContextGenNodeID()
16093
// - DockContextAddNode()
16094
// - DockContextRemoveNode()
16095
// - ImGuiDockContextPruneNodeData
16096
// - DockContextPruneUnusedSettingsNodes()
16097
// - DockContextBuildNodesFromSettings()
16098
// - DockContextBuildAddWindowsToNodes()
16099
//-----------------------------------------------------------------------------
16100
16101
void ImGui::DockContextInitialize(ImGuiContext* ctx)
16102
1
{
16103
1
    ImGuiContext& g = *ctx;
16104
16105
    // Add .ini handle for persistent docking data
16106
1
    ImGuiSettingsHandler ini_handler;
16107
1
    ini_handler.TypeName = "Docking";
16108
1
    ini_handler.TypeHash = ImHashStr("Docking");
16109
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
16110
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
16111
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
16112
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
16113
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
16114
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
16115
1
    g.SettingsHandlers.push_back(ini_handler);
16116
16117
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
16118
1
}
16119
16120
void ImGui::DockContextShutdown(ImGuiContext* ctx)
16121
0
{
16122
0
    ImGuiDockContext* dc = &ctx->DockContext;
16123
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16124
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16125
0
            IM_DELETE(node);
16126
0
}
16127
16128
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
16129
0
{
16130
0
    IM_UNUSED(ctx);
16131
0
    IM_ASSERT(ctx == GImGui);
16132
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
16133
0
    DockBuilderRemoveNodeChildNodes(root_id);
16134
0
}
16135
16136
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
16137
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
16138
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
16139
0
{
16140
0
    ImGuiContext& g = *ctx;
16141
0
    ImGuiDockContext* dc = &ctx->DockContext;
16142
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
16143
0
    SaveIniSettingsToMemory();
16144
0
    ImGuiID root_id = 0; // Rebuild all
16145
0
    DockContextClearNodes(ctx, root_id, false);
16146
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
16147
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
16148
0
}
16149
16150
// Docking context update function, called by NewFrame()
16151
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
16152
138k
{
16153
138k
    ImGuiContext& g = *ctx;
16154
138k
    ImGuiDockContext* dc = &ctx->DockContext;
16155
138k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16156
0
    {
16157
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
16158
0
            DockContextClearNodes(ctx, 0, true);
16159
0
        return;
16160
0
    }
16161
16162
    // Setting NoSplit at runtime merges all nodes
16163
138k
    if (g.IO.ConfigDockingNoSplit)
16164
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
16165
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16166
0
                if (node->IsRootNode() && node->IsSplitNode())
16167
0
                {
16168
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
16169
                    //dc->WantFullRebuild = true;
16170
0
                }
16171
16172
    // Process full rebuild
16173
#if 0
16174
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
16175
        dc->WantFullRebuild = true;
16176
#endif
16177
138k
    if (dc->WantFullRebuild)
16178
0
    {
16179
0
        DockContextRebuildNodes(ctx);
16180
0
        dc->WantFullRebuild = false;
16181
0
    }
16182
16183
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
16184
138k
    for (ImGuiDockRequest& req : dc->Requests)
16185
0
    {
16186
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
16187
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
16188
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
16189
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
16190
0
    }
16191
138k
}
16192
16193
// Docking context update function, called by NewFrame()
16194
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
16195
138k
{
16196
138k
    ImGuiContext& g = *ctx;
16197
138k
    ImGuiDockContext* dc = &ctx->DockContext;
16198
138k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16199
0
        return;
16200
16201
    // [DEBUG] Store hovered dock node.
16202
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
16203
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
16204
138k
    g.DebugHoveredDockNode = NULL;
16205
138k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
16206
774
    {
16207
774
        if (hovered_window->DockNodeAsHost)
16208
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
16209
774
        else if (hovered_window->RootWindow->DockNode)
16210
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
16211
774
    }
16212
16213
    // Process Docking requests
16214
138k
    for (ImGuiDockRequest& req : dc->Requests)
16215
0
        if (req.Type == ImGuiDockRequestType_Dock)
16216
0
            DockContextProcessDock(ctx, &req);
16217
138k
    dc->Requests.resize(0);
16218
16219
    // Create windows for each automatic docking nodes
16220
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
16221
138k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16222
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16223
0
            if (node->IsFloatingNode())
16224
0
                DockNodeUpdate(node);
16225
138k
}
16226
16227
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
16228
138k
{
16229
    // Draw backgrounds of node missing their window
16230
138k
    ImGuiContext& g = *ctx;
16231
138k
    ImGuiDockContext* dc = &g.DockContext;
16232
138k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16233
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16234
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
16235
0
            {
16236
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
16237
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
16238
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16239
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
16240
0
            }
16241
138k
}
16242
16243
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
16244
0
{
16245
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
16246
0
}
16247
16248
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
16249
0
{
16250
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
16251
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
16252
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
16253
0
    ImGuiID id = 0x0001;
16254
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
16255
0
        id++;
16256
0
    return id;
16257
0
}
16258
16259
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
16260
0
{
16261
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
16262
0
    ImGuiContext& g = *ctx;
16263
0
    if (id == 0)
16264
0
        id = DockContextGenNodeID(ctx);
16265
0
    else
16266
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
16267
16268
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
16269
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
16270
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
16271
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
16272
0
    return node;
16273
0
}
16274
16275
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
16276
0
{
16277
0
    ImGuiContext& g = *ctx;
16278
0
    ImGuiDockContext* dc = &ctx->DockContext;
16279
16280
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
16281
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
16282
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
16283
0
    IM_ASSERT(node->Windows.Size == 0);
16284
16285
0
    if (node->HostWindow)
16286
0
        node->HostWindow->DockNodeAsHost = NULL;
16287
16288
0
    ImGuiDockNode* parent_node = node->ParentNode;
16289
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
16290
0
    if (merge)
16291
0
    {
16292
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
16293
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
16294
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
16295
0
    }
16296
0
    else
16297
0
    {
16298
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
16299
0
            if (parent_node->ChildNodes[n] == node)
16300
0
                node->ParentNode->ChildNodes[n] = NULL;
16301
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
16302
0
        IM_DELETE(node);
16303
0
    }
16304
0
}
16305
16306
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
16307
0
{
16308
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
16309
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
16310
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
16311
0
}
16312
16313
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
16314
struct ImGuiDockContextPruneNodeData
16315
{
16316
    int         CountWindows, CountChildWindows, CountChildNodes;
16317
    ImGuiID     RootId;
16318
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16319
};
16320
16321
// Garbage collect unused nodes (run once at init time)
16322
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16323
0
{
16324
0
    ImGuiContext& g = *ctx;
16325
0
    ImGuiDockContext* dc = &ctx->DockContext;
16326
0
    IM_ASSERT(g.Windows.Size == 0);
16327
16328
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16329
0
    pool.Reserve(dc->NodesSettings.Size);
16330
16331
    // Count child nodes and compute RootID
16332
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16333
0
    {
16334
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16335
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16336
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16337
0
        if (settings->ParentNodeId)
16338
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16339
0
    }
16340
16341
    // Count reference to dock ids from dockspaces
16342
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16343
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16344
0
    {
16345
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16346
0
        if (settings->ParentWindowId != 0)
16347
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16348
0
                if (window_settings->DockId)
16349
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16350
0
                        data->CountChildNodes++;
16351
0
    }
16352
16353
    // Count reference to dock ids from window settings
16354
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16355
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16356
0
        if (ImGuiID dock_id = settings->DockId)
16357
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16358
0
            {
16359
0
                data->CountWindows++;
16360
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16361
0
                    data_root->CountChildWindows++;
16362
0
            }
16363
16364
    // Prune
16365
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16366
0
    {
16367
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16368
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16369
0
        if (data->CountWindows > 1)
16370
0
            continue;
16371
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16372
16373
0
        bool remove = false;
16374
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16375
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16376
0
        remove |= (data_root->CountChildWindows == 0);
16377
0
        if (remove)
16378
0
        {
16379
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16380
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16381
0
            settings->ID = 0;
16382
0
        }
16383
0
    }
16384
0
}
16385
16386
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16387
0
{
16388
    // Build nodes
16389
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16390
0
    {
16391
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16392
0
        if (settings->ID == 0)
16393
0
            continue;
16394
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16395
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16396
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16397
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16398
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16399
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16400
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16401
0
            node->ParentNode->ChildNodes[0] = node;
16402
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16403
0
            node->ParentNode->ChildNodes[1] = node;
16404
0
        node->SelectedTabId = settings->SelectedTabId;
16405
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16406
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16407
16408
        // Bind host window immediately if it already exist (in case of a rebuild)
16409
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16410
0
        char host_window_title[20];
16411
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16412
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16413
0
    }
16414
0
}
16415
16416
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16417
0
{
16418
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16419
0
    ImGuiContext& g = *ctx;
16420
0
    for (ImGuiWindow* window : g.Windows)
16421
0
    {
16422
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16423
0
            continue;
16424
0
        if (window->DockNode != NULL)
16425
0
            continue;
16426
16427
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16428
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16429
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16430
0
            DockNodeAddWindow(node, window, true);
16431
0
    }
16432
0
}
16433
16434
//-----------------------------------------------------------------------------
16435
// Docking: ImGuiDockContext Docking/Undocking functions
16436
//-----------------------------------------------------------------------------
16437
// - DockContextQueueDock()
16438
// - DockContextQueueUndockWindow()
16439
// - DockContextQueueUndockNode()
16440
// - DockContextQueueNotifyRemovedNode()
16441
// - DockContextProcessDock()
16442
// - DockContextProcessUndockWindow()
16443
// - DockContextProcessUndockNode()
16444
// - DockContextCalcDropPosForDocking()
16445
//-----------------------------------------------------------------------------
16446
16447
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16448
0
{
16449
0
    IM_ASSERT(target != payload);
16450
0
    ImGuiDockRequest req;
16451
0
    req.Type = ImGuiDockRequestType_Dock;
16452
0
    req.DockTargetWindow = target;
16453
0
    req.DockTargetNode = target_node;
16454
0
    req.DockPayload = payload;
16455
0
    req.DockSplitDir = split_dir;
16456
0
    req.DockSplitRatio = split_ratio;
16457
0
    req.DockSplitOuter = split_outer;
16458
0
    ctx->DockContext.Requests.push_back(req);
16459
0
}
16460
16461
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16462
0
{
16463
0
    ImGuiDockRequest req;
16464
0
    req.Type = ImGuiDockRequestType_Undock;
16465
0
    req.UndockTargetWindow = window;
16466
0
    ctx->DockContext.Requests.push_back(req);
16467
0
}
16468
16469
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16470
0
{
16471
0
    ImGuiDockRequest req;
16472
0
    req.Type = ImGuiDockRequestType_Undock;
16473
0
    req.UndockTargetNode = node;
16474
0
    ctx->DockContext.Requests.push_back(req);
16475
0
}
16476
16477
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16478
0
{
16479
0
    ImGuiDockContext* dc = &ctx->DockContext;
16480
0
    for (ImGuiDockRequest& req : dc->Requests)
16481
0
        if (req.DockTargetNode == node)
16482
0
            req.Type = ImGuiDockRequestType_None;
16483
0
}
16484
16485
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16486
0
{
16487
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16488
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16489
16490
0
    ImGuiContext& g = *ctx;
16491
0
    IM_UNUSED(g);
16492
16493
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16494
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16495
0
    ImGuiDockNode* node = req->DockTargetNode;
16496
0
    if (payload_window)
16497
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16498
0
    else
16499
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16500
16501
    // Decide which Tab will be selected at the end of the operation
16502
0
    ImGuiID next_selected_id = 0;
16503
0
    ImGuiDockNode* payload_node = NULL;
16504
0
    if (payload_window)
16505
0
    {
16506
0
        payload_node = payload_window->DockNodeAsHost;
16507
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16508
0
        if (payload_node && payload_node->IsLeafNode())
16509
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16510
0
        if (payload_node == NULL)
16511
0
            next_selected_id = payload_window->TabId;
16512
0
    }
16513
16514
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16515
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16516
0
    if (node)
16517
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16518
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16519
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16520
16521
    // Create new node and add existing window to it
16522
0
    if (node == NULL)
16523
0
    {
16524
0
        node = DockContextAddNode(ctx, 0);
16525
0
        node->Pos = target_window->Pos;
16526
0
        node->Size = target_window->Size;
16527
0
        if (target_window->DockNodeAsHost == NULL)
16528
0
        {
16529
0
            DockNodeAddWindow(node, target_window, true);
16530
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16531
0
            target_window->DockIsActive = true;
16532
0
        }
16533
0
    }
16534
16535
0
    ImGuiDir split_dir = req->DockSplitDir;
16536
0
    if (split_dir != ImGuiDir_None)
16537
0
    {
16538
        // Split into two, one side will be our payload node unless we are dropping a loose window
16539
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16540
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16541
0
        const float split_ratio = req->DockSplitRatio;
16542
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16543
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16544
0
        new_node->HostWindow = node->HostWindow;
16545
0
        node = new_node;
16546
0
    }
16547
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16548
16549
0
    if (node != payload_node)
16550
0
    {
16551
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16552
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16553
0
        {
16554
0
            DockNodeAddTabBar(node);
16555
0
            for (int n = 0; n < node->Windows.Size; n++)
16556
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16557
0
        }
16558
16559
0
        if (payload_node != NULL)
16560
0
        {
16561
            // Transfer full payload node (with 1+ child windows or child nodes)
16562
0
            if (payload_node->IsSplitNode())
16563
0
            {
16564
0
                if (node->Windows.Size > 0)
16565
0
                {
16566
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16567
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16568
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16569
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16570
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16571
0
                    if (visible_node->TabBar)
16572
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16573
0
                    DockNodeMoveWindows(node, visible_node);
16574
0
                    DockNodeMoveWindows(visible_node, node);
16575
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16576
0
                }
16577
0
                if (node->IsCentralNode())
16578
0
                {
16579
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16580
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16581
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16582
0
                    IM_ASSERT(last_focused_node != NULL);
16583
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16584
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16585
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16586
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16587
0
                    last_focused_root_node->CentralNode = last_focused_node;
16588
0
                }
16589
16590
0
                IM_ASSERT(node->Windows.Size == 0);
16591
0
                DockNodeMoveChildNodes(node, payload_node);
16592
0
            }
16593
0
            else
16594
0
            {
16595
0
                const ImGuiID payload_dock_id = payload_node->ID;
16596
0
                DockNodeMoveWindows(node, payload_node);
16597
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16598
0
            }
16599
0
            DockContextRemoveNode(ctx, payload_node, true);
16600
0
        }
16601
0
        else if (payload_window)
16602
0
        {
16603
            // Transfer single window
16604
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16605
0
            node->VisibleWindow = payload_window;
16606
0
            DockNodeAddWindow(node, payload_window, true);
16607
0
            if (payload_dock_id != 0)
16608
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16609
0
        }
16610
0
    }
16611
0
    else
16612
0
    {
16613
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16614
0
        node->WantHiddenTabBarUpdate = true;
16615
0
    }
16616
16617
    // Update selection immediately
16618
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16619
0
        tab_bar->NextSelectedTabId = next_selected_id;
16620
0
    MarkIniSettingsDirty();
16621
0
}
16622
16623
// Problem:
16624
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16625
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16626
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16627
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16628
// Solution:
16629
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16630
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16631
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16632
0
{
16633
0
    if (ref_viewport == NULL)
16634
0
        return size;
16635
16636
0
    ImGuiContext& g = *GImGui;
16637
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16638
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16639
0
    {
16640
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16641
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16642
0
    }
16643
0
    return ImMin(size, max_size);
16644
0
}
16645
16646
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16647
0
{
16648
0
    ImGuiContext& g = *ctx;
16649
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16650
0
    if (window->DockNode)
16651
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16652
0
    else
16653
0
        window->DockId = 0;
16654
0
    window->Collapsed = false;
16655
0
    window->DockIsActive = false;
16656
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16657
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16658
16659
0
    MarkIniSettingsDirty();
16660
0
}
16661
16662
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16663
0
{
16664
0
    ImGuiContext& g = *ctx;
16665
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16666
0
    IM_ASSERT(node->IsLeafNode());
16667
0
    IM_ASSERT(node->Windows.Size >= 1);
16668
16669
0
    if (node->IsRootNode() || node->IsCentralNode())
16670
0
    {
16671
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16672
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16673
0
        new_node->Pos = node->Pos;
16674
0
        new_node->Size = node->Size;
16675
0
        new_node->SizeRef = node->SizeRef;
16676
0
        DockNodeMoveWindows(new_node, node);
16677
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16678
0
        node = new_node;
16679
0
    }
16680
0
    else
16681
0
    {
16682
        // Otherwise extract our node and merge our sibling back into the parent node.
16683
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16684
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16685
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16686
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16687
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16688
0
        node->ParentNode = NULL;
16689
0
    }
16690
0
    for (ImGuiWindow* window : node->Windows)
16691
0
    {
16692
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16693
0
        if (window->ParentWindow)
16694
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16695
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16696
0
    }
16697
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16698
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16699
0
    node->WantMouseMove = true;
16700
0
    MarkIniSettingsDirty();
16701
0
}
16702
16703
// This is mostly used for automation.
16704
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16705
0
{
16706
0
    if (target != NULL && target_node == NULL)
16707
0
        target_node = target->DockNode;
16708
16709
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16710
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16711
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16712
0
        split_outer = true;
16713
0
    ImGuiDockPreviewData split_data;
16714
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16715
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16716
0
        return false;
16717
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16718
0
    return true;
16719
0
}
16720
16721
//-----------------------------------------------------------------------------
16722
// Docking: ImGuiDockNode
16723
//-----------------------------------------------------------------------------
16724
// - DockNodeGetTabOrder()
16725
// - DockNodeAddWindow()
16726
// - DockNodeRemoveWindow()
16727
// - DockNodeMoveChildNodes()
16728
// - DockNodeMoveWindows()
16729
// - DockNodeApplyPosSizeToWindows()
16730
// - DockNodeHideHostWindow()
16731
// - ImGuiDockNodeFindInfoResults
16732
// - DockNodeFindInfo()
16733
// - DockNodeFindWindowByID()
16734
// - DockNodeUpdateFlagsAndCollapse()
16735
// - DockNodeUpdateHasCentralNodeFlag()
16736
// - DockNodeUpdateVisibleFlag()
16737
// - DockNodeStartMouseMovingWindow()
16738
// - DockNodeUpdate()
16739
// - DockNodeUpdateWindowMenu()
16740
// - DockNodeBeginAmendTabBar()
16741
// - DockNodeEndAmendTabBar()
16742
// - DockNodeUpdateTabBar()
16743
// - DockNodeAddTabBar()
16744
// - DockNodeRemoveTabBar()
16745
// - DockNodeIsDropAllowedOne()
16746
// - DockNodeIsDropAllowed()
16747
// - DockNodeCalcTabBarLayout()
16748
// - DockNodeCalcSplitRects()
16749
// - DockNodeCalcDropRectsAndTestMousePos()
16750
// - DockNodePreviewDockSetup()
16751
// - DockNodePreviewDockRender()
16752
//-----------------------------------------------------------------------------
16753
16754
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16755
0
{
16756
0
    ID = id;
16757
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16758
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16759
0
    TabBar = NULL;
16760
0
    SplitAxis = ImGuiAxis_None;
16761
16762
0
    State = ImGuiDockNodeState_Unknown;
16763
0
    LastBgColor = IM_COL32_WHITE;
16764
0
    HostWindow = VisibleWindow = NULL;
16765
0
    CentralNode = OnlyNodeWithWindows = NULL;
16766
0
    CountNodeWithWindows = 0;
16767
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16768
0
    LastFocusedNodeId = 0;
16769
0
    SelectedTabId = 0;
16770
0
    WantCloseTabId = 0;
16771
0
    RefViewportId = 0;
16772
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16773
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16774
0
    IsVisible = true;
16775
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16776
0
    IsBgDrawnThisFrame = false;
16777
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16778
0
}
16779
16780
ImGuiDockNode::~ImGuiDockNode()
16781
0
{
16782
0
    IM_DELETE(TabBar);
16783
0
    TabBar = NULL;
16784
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16785
0
}
16786
16787
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16788
0
{
16789
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16790
0
    if (tab_bar == NULL)
16791
0
        return -1;
16792
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16793
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16794
0
}
16795
16796
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16797
0
{
16798
0
    window->Hidden = true;
16799
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16800
0
}
16801
16802
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16803
0
{
16804
0
    ImGuiContext& g = *GImGui; (void)g;
16805
0
    if (window->DockNode)
16806
0
    {
16807
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16808
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16809
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16810
0
    }
16811
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16812
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16813
16814
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16815
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16816
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16817
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16818
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16819
16820
0
    node->Windows.push_back(window);
16821
0
    node->WantHiddenTabBarUpdate = true;
16822
0
    window->DockNode = node;
16823
0
    window->DockId = node->ID;
16824
0
    window->DockIsActive = (node->Windows.Size > 1);
16825
0
    window->DockTabWantClose = false;
16826
16827
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16828
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16829
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16830
0
    {
16831
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16832
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16833
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16834
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16835
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16836
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16837
0
    }
16838
16839
    // Add to tab bar if requested
16840
0
    if (add_to_tab_bar)
16841
0
    {
16842
0
        if (node->TabBar == NULL)
16843
0
        {
16844
0
            DockNodeAddTabBar(node);
16845
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16846
16847
            // Add existing windows
16848
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16849
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16850
0
        }
16851
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16852
0
    }
16853
16854
0
    DockNodeUpdateVisibleFlag(node);
16855
16856
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16857
0
    if (node->HostWindow)
16858
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16859
0
}
16860
16861
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16862
0
{
16863
0
    ImGuiContext& g = *GImGui;
16864
0
    IM_ASSERT(window->DockNode == node);
16865
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16866
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16867
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16868
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16869
16870
0
    window->DockNode = NULL;
16871
0
    window->DockIsActive = window->DockTabWantClose = false;
16872
0
    window->DockId = save_dock_id;
16873
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16874
0
    if (window->ParentWindow)
16875
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16876
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16877
16878
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16879
0
    {
16880
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16881
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16882
0
        window->Viewport = NULL;
16883
0
        window->ViewportId = 0;
16884
0
        window->ViewportOwned = false;
16885
0
        window->Hidden = true;
16886
0
    }
16887
16888
    // Remove window
16889
0
    bool erased = false;
16890
0
    for (int n = 0; n < node->Windows.Size; n++)
16891
0
        if (node->Windows[n] == window)
16892
0
        {
16893
0
            node->Windows.erase(node->Windows.Data + n);
16894
0
            erased = true;
16895
0
            break;
16896
0
        }
16897
0
    if (!erased)
16898
0
        IM_ASSERT(erased);
16899
0
    if (node->VisibleWindow == window)
16900
0
        node->VisibleWindow = NULL;
16901
16902
    // Remove tab and possibly tab bar
16903
0
    node->WantHiddenTabBarUpdate = true;
16904
0
    if (node->TabBar)
16905
0
    {
16906
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16907
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16908
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16909
0
            DockNodeRemoveTabBar(node);
16910
0
    }
16911
16912
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16913
0
    {
16914
        // Automatic dock node delete themselves if they are not holding at least one tab
16915
0
        DockContextRemoveNode(&g, node, true);
16916
0
        return;
16917
0
    }
16918
16919
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16920
0
    {
16921
0
        ImGuiWindow* remaining_window = node->Windows[0];
16922
        // Note: we used to transport viewport ownership here.
16923
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16924
0
    }
16925
16926
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16927
0
    DockNodeUpdateVisibleFlag(node);
16928
0
}
16929
16930
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16931
0
{
16932
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16933
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16934
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16935
0
    if (dst_node->ChildNodes[0])
16936
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16937
0
    if (dst_node->ChildNodes[1])
16938
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16939
0
    dst_node->SplitAxis = src_node->SplitAxis;
16940
0
    dst_node->SizeRef = src_node->SizeRef;
16941
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16942
0
}
16943
16944
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16945
0
{
16946
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16947
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16948
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16949
0
    if (src_tab_bar != NULL)
16950
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16951
16952
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16953
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16954
0
    if (move_tab_bar)
16955
0
    {
16956
0
        dst_node->TabBar = src_node->TabBar;
16957
0
        src_node->TabBar = NULL;
16958
0
    }
16959
16960
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16961
0
    for (ImGuiWindow* window : src_node->Windows)
16962
0
    {
16963
0
        window->DockNode = NULL;
16964
0
        window->DockIsActive = false;
16965
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16966
0
    }
16967
0
    src_node->Windows.clear();
16968
16969
0
    if (!move_tab_bar && src_node->TabBar)
16970
0
    {
16971
0
        if (dst_node->TabBar)
16972
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16973
0
        DockNodeRemoveTabBar(src_node);
16974
0
    }
16975
0
}
16976
16977
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16978
0
{
16979
0
    for (ImGuiWindow* window : node->Windows)
16980
0
    {
16981
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16982
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16983
0
    }
16984
0
}
16985
16986
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16987
0
{
16988
0
    if (node->HostWindow)
16989
0
    {
16990
0
        if (node->HostWindow->DockNodeAsHost == node)
16991
0
            node->HostWindow->DockNodeAsHost = NULL;
16992
0
        node->HostWindow = NULL;
16993
0
    }
16994
16995
0
    if (node->Windows.Size == 1)
16996
0
    {
16997
0
        node->VisibleWindow = node->Windows[0];
16998
0
        node->Windows[0]->DockIsActive = false;
16999
0
    }
17000
17001
0
    if (node->TabBar)
17002
0
        DockNodeRemoveTabBar(node);
17003
0
}
17004
17005
// Search function called once by root node in DockNodeUpdate()
17006
struct ImGuiDockNodeTreeInfo
17007
{
17008
    ImGuiDockNode*      CentralNode;
17009
    ImGuiDockNode*      FirstNodeWithWindows;
17010
    int                 CountNodesWithWindows;
17011
    //ImGuiWindowClass  WindowClassForMerges;
17012
17013
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
17014
};
17015
17016
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
17017
0
{
17018
0
    if (node->Windows.Size > 0)
17019
0
    {
17020
0
        if (info->FirstNodeWithWindows == NULL)
17021
0
            info->FirstNodeWithWindows = node;
17022
0
        info->CountNodesWithWindows++;
17023
0
    }
17024
0
    if (node->IsCentralNode())
17025
0
    {
17026
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
17027
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
17028
0
        info->CentralNode = node;
17029
0
    }
17030
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
17031
0
        return;
17032
0
    if (node->ChildNodes[0])
17033
0
        DockNodeFindInfo(node->ChildNodes[0], info);
17034
0
    if (node->ChildNodes[1])
17035
0
        DockNodeFindInfo(node->ChildNodes[1], info);
17036
0
}
17037
17038
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
17039
0
{
17040
0
    IM_ASSERT(id != 0);
17041
0
    for (ImGuiWindow* window : node->Windows)
17042
0
        if (window->ID == id)
17043
0
            return window;
17044
0
    return NULL;
17045
0
}
17046
17047
// - Remove inactive windows/nodes.
17048
// - Update visibility flag.
17049
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
17050
0
{
17051
0
    ImGuiContext& g = *GImGui;
17052
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17053
17054
    // Inherit most flags
17055
0
    if (node->ParentNode)
17056
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17057
17058
    // Recurse into children
17059
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
17060
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
17061
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
17062
0
    node->HasCentralNodeChild = false;
17063
0
    if (node->ChildNodes[0])
17064
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
17065
0
    if (node->ChildNodes[1])
17066
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
17067
17068
    // Remove inactive windows, collapse nodes
17069
    // Merge node flags overrides stored in windows
17070
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17071
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17072
0
    {
17073
0
        ImGuiWindow* window = node->Windows[window_n];
17074
0
        IM_ASSERT(window->DockNode == node);
17075
17076
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17077
0
        bool remove = false;
17078
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
17079
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
17080
0
        remove |= (window->DockTabWantClose);
17081
0
        if (remove)
17082
0
        {
17083
0
            window->DockTabWantClose = false;
17084
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
17085
0
            {
17086
0
                DockNodeHideHostWindow(node);
17087
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17088
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
17089
0
                return;
17090
0
            }
17091
0
            DockNodeRemoveWindow(node, window, node->ID);
17092
0
            window_n--;
17093
0
            continue;
17094
0
        }
17095
17096
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
17097
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
17098
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
17099
0
    }
17100
0
    node->UpdateMergedFlags();
17101
17102
    // Auto-hide tab bar option
17103
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
17104
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
17105
0
        node->WantHiddenTabBarToggle = true;
17106
0
    node->WantHiddenTabBarUpdate = false;
17107
17108
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
17109
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
17110
0
        node->WantHiddenTabBarToggle = false;
17111
17112
    // Apply toggles at a single point of the frame (here!)
17113
0
    if (node->Windows.Size > 1)
17114
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17115
0
    else if (node->WantHiddenTabBarToggle)
17116
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
17117
0
    node->WantHiddenTabBarToggle = false;
17118
17119
0
    DockNodeUpdateVisibleFlag(node);
17120
0
}
17121
17122
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
17123
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
17124
0
{
17125
0
    node->HasCentralNodeChild = false;
17126
0
    if (node->ChildNodes[0])
17127
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
17128
0
    if (node->ChildNodes[1])
17129
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
17130
0
    if (node->IsRootNode())
17131
0
    {
17132
0
        ImGuiDockNode* mark_node = node->CentralNode;
17133
0
        while (mark_node)
17134
0
        {
17135
0
            mark_node->HasCentralNodeChild = true;
17136
0
            mark_node = mark_node->ParentNode;
17137
0
        }
17138
0
    }
17139
0
}
17140
17141
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
17142
0
{
17143
    // Update visibility flag
17144
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
17145
0
    is_visible |= (node->Windows.Size > 0);
17146
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
17147
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
17148
0
    node->IsVisible = is_visible;
17149
0
}
17150
17151
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
17152
0
{
17153
0
    ImGuiContext& g = *GImGui;
17154
0
    IM_ASSERT(node->WantMouseMove == true);
17155
0
    StartMouseMovingWindow(window);
17156
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
17157
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
17158
0
    node->WantMouseMove = false;
17159
0
}
17160
17161
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
17162
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
17163
0
{
17164
0
    DockNodeUpdateFlagsAndCollapse(node);
17165
17166
    // - Setup central node pointers
17167
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
17168
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
17169
0
    ImGuiDockNodeTreeInfo info;
17170
0
    DockNodeFindInfo(node, &info);
17171
0
    node->CentralNode = info.CentralNode;
17172
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
17173
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
17174
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
17175
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
17176
17177
    // Copy the window class from of our first window so it can be used for proper dock filtering.
17178
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
17179
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
17180
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
17181
0
    {
17182
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
17183
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
17184
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
17185
0
            {
17186
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
17187
0
                break;
17188
0
            }
17189
0
    }
17190
17191
0
    ImGuiDockNode* mark_node = node->CentralNode;
17192
0
    while (mark_node)
17193
0
    {
17194
0
        mark_node->HasCentralNodeChild = true;
17195
0
        mark_node = mark_node->ParentNode;
17196
0
    }
17197
0
}
17198
17199
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
17200
0
{
17201
    // Remove ourselves from any previous different host window
17202
    // This can happen if a user mistakenly does (see #4295 for details):
17203
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
17204
    //  - N+1: NewFrame()                   // will create floating host window for that node
17205
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
17206
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
17207
0
        node->HostWindow->DockNodeAsHost = NULL;
17208
17209
0
    host_window->DockNodeAsHost = node;
17210
0
    node->HostWindow = host_window;
17211
0
}
17212
17213
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
17214
0
{
17215
0
    ImGuiContext& g = *GImGui;
17216
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
17217
0
    node->LastFrameAlive = g.FrameCount;
17218
0
    node->IsBgDrawnThisFrame = false;
17219
17220
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
17221
0
    if (node->IsRootNode())
17222
0
        DockNodeUpdateForRootNode(node);
17223
17224
    // Remove tab bar if not needed
17225
0
    if (node->TabBar && node->IsNoTabBar())
17226
0
        DockNodeRemoveTabBar(node);
17227
17228
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
17229
0
    bool want_to_hide_host_window = false;
17230
0
    if (node->IsFloatingNode())
17231
0
    {
17232
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
17233
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
17234
0
                want_to_hide_host_window = true;
17235
0
        if (node->CountNodeWithWindows == 0)
17236
0
            want_to_hide_host_window = true;
17237
0
    }
17238
0
    if (want_to_hide_host_window)
17239
0
    {
17240
0
        if (node->Windows.Size == 1)
17241
0
        {
17242
            // Floating window pos/size is authoritative
17243
0
            ImGuiWindow* single_window = node->Windows[0];
17244
0
            node->Pos = single_window->Pos;
17245
0
            node->Size = single_window->SizeFull;
17246
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17247
17248
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
17249
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
17250
0
                FocusWindow(single_window);
17251
0
            if (node->HostWindow)
17252
0
            {
17253
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
17254
0
                single_window->Viewport = node->HostWindow->Viewport;
17255
0
                single_window->ViewportId = node->HostWindow->ViewportId;
17256
0
                if (node->HostWindow->ViewportOwned)
17257
0
                {
17258
0
                    single_window->Viewport->ID = single_window->ID;
17259
0
                    single_window->Viewport->Window = single_window;
17260
0
                    single_window->ViewportOwned = true;
17261
0
                }
17262
0
            }
17263
0
            node->RefViewportId = single_window->ViewportId;
17264
0
        }
17265
17266
0
        DockNodeHideHostWindow(node);
17267
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17268
0
        node->WantCloseAll = false;
17269
0
        node->WantCloseTabId = 0;
17270
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
17271
0
        node->LastFrameActive = g.FrameCount;
17272
17273
0
        if (node->WantMouseMove && node->Windows.Size == 1)
17274
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
17275
0
        return;
17276
0
    }
17277
17278
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
17279
    // while the expected visible window is resizing itself.
17280
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
17281
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
17282
    //   N+0: Begin(): window created (with no known size), node is created
17283
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
17284
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
17285
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
17286
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
17287
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
17288
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
17289
0
    {
17290
0
        IM_ASSERT(node->Windows.Size > 0);
17291
0
        ImGuiWindow* ref_window = NULL;
17292
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
17293
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
17294
0
        if (ref_window == NULL)
17295
0
            ref_window = node->Windows[0];
17296
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
17297
0
        {
17298
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
17299
0
            return;
17300
0
        }
17301
0
    }
17302
17303
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17304
17305
    // Decide if the node will have a close button and a window menu button
17306
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
17307
0
    node->HasCloseButton = false;
17308
0
    for (ImGuiWindow* window : node->Windows)
17309
0
    {
17310
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
17311
0
        node->HasCloseButton |= window->HasCloseButton;
17312
0
        window->DockIsActive = (node->Windows.Size > 1);
17313
0
    }
17314
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17315
0
        node->HasCloseButton = false;
17316
17317
    // Bind or create host window
17318
0
    ImGuiWindow* host_window = NULL;
17319
0
    bool beginned_into_host_window = false;
17320
0
    if (node->IsDockSpace())
17321
0
    {
17322
        // [Explicit root dockspace node]
17323
0
        IM_ASSERT(node->HostWindow);
17324
0
        host_window = node->HostWindow;
17325
0
    }
17326
0
    else
17327
0
    {
17328
        // [Automatic root or child nodes]
17329
0
        if (node->IsRootNode() && node->IsVisible)
17330
0
        {
17331
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17332
17333
            // Sync Pos
17334
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17335
0
                SetNextWindowPos(ref_window->Pos);
17336
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17337
0
                SetNextWindowPos(node->Pos);
17338
17339
            // Sync Size
17340
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17341
0
                SetNextWindowSize(ref_window->SizeFull);
17342
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17343
0
                SetNextWindowSize(node->Size);
17344
17345
            // Sync Collapsed
17346
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17347
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17348
17349
            // Sync Viewport
17350
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17351
0
                SetNextWindowViewport(ref_window->ViewportId);
17352
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17353
0
                SetNextWindowViewport(node->RefViewportId);
17354
17355
0
            SetNextWindowClass(&node->WindowClass);
17356
17357
            // Begin into the host window
17358
0
            char window_label[20];
17359
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17360
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17361
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17362
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17363
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17364
17365
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17366
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17367
0
            Begin(window_label, NULL, window_flags);
17368
0
            PopStyleVar();
17369
0
            beginned_into_host_window = true;
17370
17371
0
            host_window = g.CurrentWindow;
17372
0
            DockNodeSetupHostWindow(node, host_window);
17373
0
            host_window->DC.CursorPos = host_window->Pos;
17374
0
            node->Pos = host_window->Pos;
17375
0
            node->Size = host_window->Size;
17376
17377
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17378
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17379
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17380
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17381
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17382
            // after the dock host window, losing their top-most status.
17383
0
            if (node->HostWindow->Appearing)
17384
0
                BringWindowToDisplayFront(node->HostWindow);
17385
17386
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17387
0
        }
17388
0
        else if (node->ParentNode)
17389
0
        {
17390
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17391
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17392
0
        }
17393
0
        if (node->WantMouseMove && node->HostWindow)
17394
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17395
0
    }
17396
0
    node->RefViewportId = 0; // Clear when we have a host window
17397
17398
    // Update focused node (the one whose title bar is highlight) within a node tree
17399
0
    if (node->IsSplitNode())
17400
0
        IM_ASSERT(node->TabBar == NULL);
17401
0
    if (node->IsRootNode())
17402
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17403
0
            while (p_window != NULL && p_window->DockNode != NULL)
17404
0
            {
17405
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17406
0
                if (p_node == node)
17407
0
                {
17408
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17409
0
                    break;
17410
0
                }
17411
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17412
0
            }
17413
17414
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17415
0
    ImGuiDockNode* central_node = node->CentralNode;
17416
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17417
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17418
0
    if (central_node_hole)
17419
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17420
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17421
0
                central_node_hole_register_hit_test_hole = false;
17422
0
    if (central_node_hole_register_hit_test_hole)
17423
0
    {
17424
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17425
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17426
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17427
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17428
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17429
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17430
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17431
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17432
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17433
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17434
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17435
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17436
0
        if (central_node_hole && !hole_rect.IsInverted())
17437
0
        {
17438
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17439
0
            if (host_window->ParentWindow)
17440
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17441
0
        }
17442
0
    }
17443
17444
    // Update position/size, process and draw resizing splitters
17445
0
    if (node->IsRootNode() && host_window)
17446
0
    {
17447
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17448
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17449
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17450
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17451
0
        DockNodeTreeUpdateSplitter(node);
17452
0
        PopStyleColor(3);
17453
0
    }
17454
17455
    // Draw empty node background (currently can only be the Central Node)
17456
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17457
0
    {
17458
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17459
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17460
0
        if (node->LastBgColor != 0)
17461
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17462
0
        node->IsBgDrawnThisFrame = true;
17463
0
    }
17464
17465
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17466
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17467
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17468
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17469
0
    if (render_dockspace_bg && node->IsVisible)
17470
0
    {
17471
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17472
0
        if (central_node_hole)
17473
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17474
0
        else
17475
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17476
0
    }
17477
17478
    // Draw and populate Tab Bar
17479
0
    if (host_window)
17480
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17481
0
    if (host_window && node->Windows.Size > 0)
17482
0
    {
17483
0
        DockNodeUpdateTabBar(node, host_window);
17484
0
    }
17485
0
    else
17486
0
    {
17487
0
        node->WantCloseAll = false;
17488
0
        node->WantCloseTabId = 0;
17489
0
        node->IsFocused = false;
17490
0
    }
17491
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17492
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17493
0
    else if (node->Windows.Size > 0)
17494
0
        node->SelectedTabId = node->Windows[0]->TabId;
17495
17496
    // Draw payload drop target
17497
0
    if (host_window && node->IsVisible)
17498
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17499
0
            BeginDockableDragDropTarget(host_window);
17500
17501
    // We update this after DockNodeUpdateTabBar()
17502
0
    node->LastFrameActive = g.FrameCount;
17503
17504
    // Recurse into children
17505
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17506
0
    if (host_window)
17507
0
    {
17508
0
        if (node->ChildNodes[0])
17509
0
            DockNodeUpdate(node->ChildNodes[0]);
17510
0
        if (node->ChildNodes[1])
17511
0
            DockNodeUpdate(node->ChildNodes[1]);
17512
17513
        // Render outer borders last (after the tab bar)
17514
0
        if (node->IsRootNode())
17515
0
            RenderWindowOuterBorders(host_window);
17516
0
    }
17517
17518
    // End host window
17519
0
    if (beginned_into_host_window) //-V1020
17520
0
        End();
17521
0
}
17522
17523
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17524
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17525
0
{
17526
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17527
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17528
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17529
0
        return d;
17530
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17531
0
}
17532
17533
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17534
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17535
// Custom overrides may want to decorate, group, sort entries.
17536
// Please note those are internal structures: if you copy this expect occasional breakage.
17537
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17538
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17539
0
{
17540
0
    IM_UNUSED(ctx);
17541
0
    if (tab_bar->Tabs.Size == 1)
17542
0
    {
17543
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17544
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17545
0
            node->WantHiddenTabBarToggle = true;
17546
0
    }
17547
0
    else
17548
0
    {
17549
        // Display a selectable list of windows in this docking node
17550
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17551
0
        {
17552
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17553
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17554
0
                continue;
17555
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17556
0
                TabBarQueueFocus(tab_bar, tab);
17557
0
            SameLine();
17558
0
            Text("   ");
17559
0
        }
17560
0
    }
17561
0
}
17562
17563
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17564
0
{
17565
    // Try to position the menu so it is more likely to stays within the same viewport
17566
0
    ImGuiContext& g = *GImGui;
17567
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17568
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17569
0
    else
17570
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17571
0
    if (BeginPopup("#WindowMenu"))
17572
0
    {
17573
0
        node->IsFocused = true;
17574
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17575
0
        EndPopup();
17576
0
    }
17577
0
}
17578
17579
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17580
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17581
0
{
17582
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17583
0
        return false;
17584
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17585
0
        return false;
17586
0
    if (node->TabBar->ID == 0)
17587
0
        return false;
17588
0
    Begin(node->HostWindow->Name);
17589
0
    PushOverrideID(node->ID);
17590
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17591
0
    IM_UNUSED(ret);
17592
0
    IM_ASSERT(ret);
17593
0
    return true;
17594
0
}
17595
17596
void ImGui::DockNodeEndAmendTabBar()
17597
0
{
17598
0
    EndTabBar();
17599
0
    PopID();
17600
0
    End();
17601
0
}
17602
17603
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17604
0
{
17605
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17606
0
    ImGuiContext& g = *GImGui;
17607
0
    if (g.NavWindowingTarget)
17608
0
        return (g.NavWindowingTarget->DockNode == node);
17609
17610
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17611
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17612
0
    {
17613
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17614
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17615
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17616
0
            parent_window = parent_window->ParentWindow->RootWindow;
17617
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17618
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17619
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17620
0
                return true;
17621
0
    }
17622
0
    return false;
17623
0
}
17624
17625
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17626
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17627
0
{
17628
0
    ImGuiContext& g = *GImGui;
17629
0
    ImGuiStyle& style = g.Style;
17630
17631
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17632
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17633
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17634
0
    node->WantCloseAll = false;
17635
0
    node->WantCloseTabId = 0;
17636
17637
    // Decide if we should use a focused title bar color
17638
0
    bool is_focused = false;
17639
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17640
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17641
0
        is_focused = true;
17642
17643
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17644
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17645
0
    {
17646
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17647
0
        node->IsFocused = is_focused;
17648
0
        if (is_focused)
17649
0
            node->LastFrameFocused = g.FrameCount;
17650
0
        if (node->VisibleWindow)
17651
0
        {
17652
            // Notify root of visible window (used to display title in OS task bar)
17653
0
            if (is_focused || root_node->VisibleWindow == NULL)
17654
0
                root_node->VisibleWindow = node->VisibleWindow;
17655
0
            if (node->TabBar)
17656
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17657
0
        }
17658
0
        return;
17659
0
    }
17660
17661
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17662
0
    bool backup_skip_item = host_window->SkipItems;
17663
0
    if (!node->IsDockSpace())
17664
0
    {
17665
0
        host_window->SkipItems = false;
17666
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17667
0
    }
17668
17669
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17670
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17671
    // as docked windows themselves will override the stack with their own root ID.
17672
0
    PushOverrideID(node->ID);
17673
0
    ImGuiTabBar* tab_bar = node->TabBar;
17674
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17675
0
    if (tab_bar == NULL)
17676
0
    {
17677
0
        DockNodeAddTabBar(node);
17678
0
        tab_bar = node->TabBar;
17679
0
    }
17680
17681
0
    ImGuiID focus_tab_id = 0;
17682
0
    node->IsFocused = is_focused;
17683
17684
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17685
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17686
17687
    // In a dock node, the Collapse Button turns into the Window Menu button.
17688
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17689
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17690
0
    {
17691
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17692
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17693
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17694
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17695
0
        is_focused |= node->IsFocused;
17696
0
    }
17697
17698
    // Layout
17699
0
    ImRect title_bar_rect, tab_bar_rect;
17700
0
    ImVec2 window_menu_button_pos;
17701
0
    ImVec2 close_button_pos;
17702
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17703
17704
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17705
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17706
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17707
0
    {
17708
0
        ImGuiWindow* window = node->Windows[window_n];
17709
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17710
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17711
0
    }
17712
17713
    // Title bar
17714
0
    if (is_focused)
17715
0
        node->LastFrameFocused = g.FrameCount;
17716
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17717
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17718
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17719
17720
    // Docking/Collapse button
17721
0
    if (has_window_menu_button)
17722
0
    {
17723
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17724
0
            OpenPopup("#WindowMenu");
17725
0
        if (IsItemActive())
17726
0
            focus_tab_id = tab_bar->SelectedTabId;
17727
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17728
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17729
0
    }
17730
17731
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17732
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17733
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17734
0
    {
17735
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17736
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17737
0
        tabs_unsorted_start = tab_n;
17738
0
    }
17739
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17740
0
    {
17741
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17742
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17743
0
        {
17744
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17745
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17746
0
        }
17747
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17748
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17749
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17750
0
    }
17751
17752
    // Apply NavWindow focus back to the tab bar
17753
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17754
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17755
17756
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17757
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17758
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17759
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17760
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17761
17762
    // Begin tab bar
17763
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17764
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17765
0
    tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
17766
0
    if (!host_window->Collapsed && is_focused)
17767
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17768
0
    tab_bar->ID = GetID("#TabBar");
17769
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17770
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17771
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17772
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17773
17774
    // Backup style colors
17775
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17776
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17777
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17778
17779
    // Submit actual tabs
17780
0
    node->VisibleWindow = NULL;
17781
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17782
0
    {
17783
0
        ImGuiWindow* window = node->Windows[window_n];
17784
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17785
0
            continue;
17786
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17787
0
        {
17788
0
            ImGuiTabItemFlags tab_item_flags = 0;
17789
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17790
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17791
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17792
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17793
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17794
17795
            // Apply stored style overrides for the window
17796
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17797
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17798
17799
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17800
0
            bool tab_open = true;
17801
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17802
0
            if (!tab_open)
17803
0
                node->WantCloseTabId = window->TabId;
17804
0
            if (tab_bar->VisibleTabId == window->TabId)
17805
0
                node->VisibleWindow = window;
17806
17807
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17808
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17809
0
            window->DockTabItemRect = g.LastItemData.Rect;
17810
17811
            // Update navigation ID on menu layer
17812
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17813
0
                host_window->NavLastIds[1] = window->TabId;
17814
0
        }
17815
0
    }
17816
17817
    // Restore style colors
17818
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17819
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17820
17821
    // Notify root of visible window (used to display title in OS task bar)
17822
0
    if (node->VisibleWindow)
17823
0
        if (is_focused || root_node->VisibleWindow == NULL)
17824
0
            root_node->VisibleWindow = node->VisibleWindow;
17825
17826
    // Close button (after VisibleWindow was updated)
17827
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17828
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17829
0
    const bool close_button_is_visible = node->HasCloseButton;
17830
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17831
0
    if (close_button_is_visible)
17832
0
    {
17833
0
        if (!close_button_is_enabled)
17834
0
        {
17835
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17836
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17837
0
        }
17838
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17839
0
        {
17840
0
            node->WantCloseAll = true;
17841
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17842
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17843
0
        }
17844
        //if (IsItemActive())
17845
        //    focus_tab_id = tab_bar->SelectedTabId;
17846
0
        if (!close_button_is_enabled)
17847
0
        {
17848
0
            PopStyleColor();
17849
0
            PopItemFlag();
17850
0
        }
17851
0
    }
17852
17853
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17854
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17855
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17856
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17857
0
    {
17858
        // AllowOverlap mode required for appending into dock node tab bar,
17859
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17860
0
        bool held;
17861
0
        KeepAliveID(title_bar_id);
17862
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17863
0
        if (g.HoveredId == title_bar_id)
17864
0
        {
17865
0
            g.LastItemData.ID = title_bar_id;
17866
0
        }
17867
0
        if (held)
17868
0
        {
17869
0
            if (IsMouseClicked(0))
17870
0
                focus_tab_id = tab_bar->SelectedTabId;
17871
17872
            // Forward moving request to selected window
17873
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17874
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17875
0
        }
17876
0
    }
17877
17878
    // Forward focus from host node to selected window
17879
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17880
    //    focus_tab_id = tab_bar->SelectedTabId;
17881
17882
    // When clicked on a tab we requested focus to the docked child
17883
    // This overrides the value set by "forward focus from host node to selected window".
17884
0
    if (tab_bar->NextSelectedTabId)
17885
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17886
17887
    // Apply navigation focus
17888
0
    if (focus_tab_id != 0)
17889
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17890
0
            if (tab->Window)
17891
0
            {
17892
0
                FocusWindow(tab->Window);
17893
0
                NavInitWindow(tab->Window, false);
17894
0
            }
17895
17896
0
    EndTabBar();
17897
0
    PopID();
17898
17899
    // Restore SkipItems flag
17900
0
    if (!node->IsDockSpace())
17901
0
    {
17902
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17903
0
        host_window->SkipItems = backup_skip_item;
17904
0
    }
17905
0
}
17906
17907
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17908
0
{
17909
0
    IM_ASSERT(node->TabBar == NULL);
17910
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17911
0
}
17912
17913
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17914
0
{
17915
0
    if (node->TabBar == NULL)
17916
0
        return;
17917
0
    IM_DELETE(node->TabBar);
17918
0
    node->TabBar = NULL;
17919
0
}
17920
17921
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17922
2
{
17923
2
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17924
0
        return false;
17925
17926
2
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17927
2
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17928
2
    if (host_class->ClassId != payload_class->ClassId)
17929
0
    {
17930
0
        bool pass = false;
17931
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17932
0
            pass = true;
17933
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17934
0
            pass = true;
17935
0
        if (!pass)
17936
0
            return false;
17937
0
    }
17938
17939
    // Prevent docking any window created above a popup
17940
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17941
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17942
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17943
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17944
2
    ImGuiContext& g = *GImGui;
17945
2
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17946
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17947
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17948
0
                return false;
17949
17950
2
    return true;
17951
2
}
17952
17953
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17954
2
{
17955
2
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17956
0
        return true;
17957
17958
2
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17959
2
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17960
2
    {
17961
2
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17962
2
        if (DockNodeIsDropAllowedOne(payload, host_window))
17963
2
            return true;
17964
2
    }
17965
0
    return false;
17966
2
}
17967
17968
// window menu button == collapse button when not in a dock node.
17969
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17970
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17971
0
{
17972
0
    ImGuiContext& g = *GImGui;
17973
0
    ImGuiStyle& style = g.Style;
17974
17975
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17976
0
    if (out_title_rect) { *out_title_rect = r; }
17977
17978
0
    r.Min.x += style.WindowBorderSize;
17979
0
    r.Max.x -= style.WindowBorderSize;
17980
17981
0
    float button_sz = g.FontSize;
17982
0
    r.Min.x += style.FramePadding.x;
17983
0
    r.Max.x -= style.FramePadding.x;
17984
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17985
0
    if (node->HasCloseButton)
17986
0
    {
17987
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17988
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17989
0
    }
17990
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17991
0
    {
17992
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17993
0
    }
17994
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17995
0
    {
17996
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17997
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17998
0
    }
17999
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
18000
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
18001
0
}
18002
18003
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
18004
0
{
18005
0
    ImGuiContext& g = *GImGui;
18006
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
18007
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18008
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
18009
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
18010
18011
    // Distribute size on given axis (with a desired size or equally)
18012
0
    const float w_avail = size_old[axis] - dock_spacing;
18013
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
18014
0
    {
18015
0
        size_new[axis] = size_new_desired[axis];
18016
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18017
0
    }
18018
0
    else
18019
0
    {
18020
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
18021
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18022
0
    }
18023
18024
    // Position each node
18025
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
18026
0
    {
18027
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
18028
0
    }
18029
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
18030
0
    {
18031
0
        pos_new[axis] = pos_old[axis];
18032
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
18033
0
    }
18034
0
}
18035
18036
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
18037
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
18038
0
{
18039
0
    ImGuiContext& g = *GImGui;
18040
18041
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
18042
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
18043
0
    float hs_w; // Half-size, longer axis
18044
0
    float hs_h; // Half-size, smaller axis
18045
0
    ImVec2 off; // Distance from edge or center
18046
0
    if (outer_docking)
18047
0
    {
18048
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
18049
        //hs_h = ImTrunc(hs_w * 0.15f);
18050
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
18051
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
18052
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
18053
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
18054
0
    }
18055
0
    else
18056
0
    {
18057
0
        hs_w = ImTrunc(hs_for_central_nodes);
18058
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
18059
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
18060
0
    }
18061
18062
0
    ImVec2 c = ImTrunc(parent.GetCenter());
18063
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
18064
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
18065
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
18066
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
18067
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
18068
18069
0
    if (test_mouse_pos == NULL)
18070
0
        return false;
18071
18072
0
    ImRect hit_r = out_r;
18073
0
    if (!outer_docking)
18074
0
    {
18075
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
18076
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
18077
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
18078
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
18079
0
        float r_threshold_center = hs_w * 1.4f;
18080
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
18081
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
18082
0
            return (dir == ImGuiDir_None);
18083
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
18084
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
18085
0
    }
18086
0
    return hit_r.Contains(*test_mouse_pos);
18087
0
}
18088
18089
// host_node may be NULL if the window doesn't have a DockNode already.
18090
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
18091
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
18092
0
{
18093
0
    ImGuiContext& g = *GImGui;
18094
18095
    // There is an edge case when docking into a dockspace which only has inactive nodes.
18096
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
18097
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
18098
0
    if (payload_node == NULL)
18099
0
        payload_node = payload_window->DockNodeAsHost;
18100
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
18101
0
    if (ref_node_for_rect)
18102
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
18103
18104
    // Filter, figure out where we are allowed to dock
18105
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
18106
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
18107
0
    data->IsCenterAvailable = true;
18108
0
    if (is_outer_docking)
18109
0
        data->IsCenterAvailable = false;
18110
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
18111
0
        data->IsCenterAvailable = false;
18112
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
18113
0
        data->IsCenterAvailable = false;
18114
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
18115
0
        data->IsCenterAvailable = false;
18116
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
18117
0
        data->IsCenterAvailable = false;
18118
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
18119
0
        data->IsCenterAvailable = false;
18120
18121
0
    data->IsSidesAvailable = true;
18122
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
18123
0
        data->IsSidesAvailable = false;
18124
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
18125
0
        data->IsSidesAvailable = false;
18126
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
18127
0
        data->IsSidesAvailable = false;
18128
18129
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
18130
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
18131
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
18132
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
18133
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
18134
18135
    // Calculate drop shapes geometry for allowed splitting directions
18136
0
    IM_ASSERT(ImGuiDir_None == -1);
18137
0
    data->SplitNode = host_node;
18138
0
    data->SplitDir = ImGuiDir_None;
18139
0
    data->IsSplitDirExplicit = false;
18140
0
    if (!host_window->Collapsed)
18141
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18142
0
        {
18143
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
18144
0
                continue;
18145
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
18146
0
                continue;
18147
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
18148
0
            {
18149
0
                data->SplitDir = (ImGuiDir)dir;
18150
0
                data->IsSplitDirExplicit = true;
18151
0
            }
18152
0
        }
18153
18154
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
18155
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
18156
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
18157
0
        data->IsDropAllowed = false;
18158
18159
    // Calculate split area
18160
0
    data->SplitRatio = 0.0f;
18161
0
    if (data->SplitDir != ImGuiDir_None)
18162
0
    {
18163
0
        ImGuiDir split_dir = data->SplitDir;
18164
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18165
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
18166
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
18167
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
18168
18169
        // Calculate split ratio so we can pass it down the docking request
18170
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
18171
0
        data->FutureNode.Pos = pos_new;
18172
0
        data->FutureNode.Size = size_new;
18173
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
18174
0
    }
18175
0
}
18176
18177
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
18178
0
{
18179
0
    ImGuiContext& g = *GImGui;
18180
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
18181
18182
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
18183
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
18184
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
18185
18186
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
18187
0
    int overlay_draw_lists_count = 0;
18188
0
    ImDrawList* overlay_draw_lists[2];
18189
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
18190
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
18191
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
18192
18193
    // Draw main preview rectangle
18194
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
18195
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
18196
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
18197
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
18198
18199
    // Display area preview
18200
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
18201
0
    if (data->IsDropAllowed)
18202
0
    {
18203
0
        ImRect overlay_rect = data->FutureNode.Rect();
18204
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
18205
0
            overlay_rect.Min.y += GetFrameHeight();
18206
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
18207
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18208
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
18209
0
    }
18210
18211
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
18212
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
18213
0
    {
18214
        // Compute target tab bar geometry so we can locate our preview tabs
18215
0
        ImRect tab_bar_rect;
18216
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
18217
0
        ImVec2 tab_pos = tab_bar_rect.Min;
18218
0
        if (host_node && host_node->TabBar)
18219
0
        {
18220
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
18221
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
18222
0
            else
18223
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
18224
0
        }
18225
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
18226
0
        {
18227
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
18228
0
        }
18229
18230
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
18231
0
        if (root_payload->DockNodeAsHost)
18232
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
18233
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
18234
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
18235
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
18236
0
        {
18237
            // DockNode's TabBar may have non-window Tabs manually appended by user
18238
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
18239
0
            if (tab_bar_with_payload && payload_window == NULL)
18240
0
                continue;
18241
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
18242
0
                continue;
18243
18244
            // Calculate the tab bounding box for each payload window
18245
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
18246
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
18247
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
18248
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
18249
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
18250
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
18251
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18252
0
            {
18253
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
18254
0
                if (!tab_bar_rect.Contains(tab_bb))
18255
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
18256
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
18257
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
18258
0
                if (!tab_bar_rect.Contains(tab_bb))
18259
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
18260
0
            }
18261
0
            PopStyleColor();
18262
0
        }
18263
0
    }
18264
18265
    // Display drop boxes
18266
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
18267
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18268
0
    {
18269
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
18270
0
        {
18271
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
18272
0
            ImRect draw_r_in = draw_r;
18273
0
            draw_r_in.Expand(-2.0f);
18274
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
18275
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18276
0
            {
18277
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
18278
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
18279
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
18280
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
18281
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
18282
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
18283
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
18284
0
            }
18285
0
        }
18286
18287
        // Stop after ImGuiDir_None
18288
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
18289
0
            return;
18290
0
    }
18291
0
}
18292
18293
//-----------------------------------------------------------------------------
18294
// Docking: ImGuiDockNode Tree manipulation functions
18295
//-----------------------------------------------------------------------------
18296
// - DockNodeTreeSplit()
18297
// - DockNodeTreeMerge()
18298
// - DockNodeTreeUpdatePosSize()
18299
// - DockNodeTreeUpdateSplitterFindTouchingNode()
18300
// - DockNodeTreeUpdateSplitter()
18301
// - DockNodeTreeFindFallbackLeafNode()
18302
// - DockNodeTreeFindNodeByPos()
18303
//-----------------------------------------------------------------------------
18304
18305
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
18306
0
{
18307
0
    ImGuiContext& g = *GImGui;
18308
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
18309
18310
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
18311
0
    child_0->ParentNode = parent_node;
18312
18313
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
18314
0
    child_1->ParentNode = parent_node;
18315
18316
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18317
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18318
0
    parent_node->ChildNodes[0] = child_0;
18319
0
    parent_node->ChildNodes[1] = child_1;
18320
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18321
0
    parent_node->SplitAxis = split_axis;
18322
0
    parent_node->VisibleWindow = NULL;
18323
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18324
18325
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18326
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18327
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18328
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18329
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18330
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18331
18332
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18333
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18334
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18335
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18336
18337
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18338
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18339
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18340
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18341
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18342
0
    child_0->UpdateMergedFlags();
18343
0
    child_1->UpdateMergedFlags();
18344
0
    parent_node->UpdateMergedFlags();
18345
0
    if (child_inheritor->IsCentralNode())
18346
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18347
0
}
18348
18349
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18350
0
{
18351
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18352
0
    ImGuiContext& g = *GImGui;
18353
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18354
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18355
0
    IM_ASSERT(child_0 || child_1);
18356
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18357
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18358
0
    {
18359
0
        IM_ASSERT(parent_node->TabBar == NULL);
18360
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18361
0
    }
18362
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18363
18364
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18365
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18366
0
    if (child_0)
18367
0
    {
18368
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18369
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18370
0
    }
18371
0
    if (child_1)
18372
0
    {
18373
0
        DockNodeMoveWindows(parent_node, child_1);
18374
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18375
0
    }
18376
0
    DockNodeApplyPosSizeToWindows(parent_node);
18377
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18378
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18379
0
    parent_node->SizeRef = backup_last_explicit_size;
18380
18381
    // Flags transfer
18382
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18383
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18384
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18385
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18386
0
    parent_node->UpdateMergedFlags();
18387
18388
0
    if (child_0)
18389
0
    {
18390
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18391
0
        IM_DELETE(child_0);
18392
0
    }
18393
0
    if (child_1)
18394
0
    {
18395
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18396
0
        IM_DELETE(child_1);
18397
0
    }
18398
0
}
18399
18400
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18401
// (Depth-first, Pre-Order)
18402
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18403
0
{
18404
    // During the regular dock node update we write to all nodes.
18405
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18406
0
    ImGuiContext& g = *GImGui;
18407
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18408
0
    if (write_to_node)
18409
0
    {
18410
0
        node->Pos = pos;
18411
0
        node->Size = size;
18412
0
    }
18413
18414
0
    if (node->IsLeafNode())
18415
0
        return;
18416
18417
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18418
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18419
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18420
0
    ImVec2 child_0_size = size, child_1_size = size;
18421
18422
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18423
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18424
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18425
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18426
18427
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18428
0
    {
18429
0
        const float spacing = g.Style.DockingSeparatorSize;
18430
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18431
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18432
18433
        // Size allocation policy
18434
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18435
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18436
18437
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18438
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18439
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18440
18441
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18442
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18443
0
        {
18444
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18445
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18446
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18447
0
        }
18448
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18449
0
        {
18450
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18451
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18452
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18453
0
        }
18454
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18455
0
        {
18456
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18457
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18458
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18459
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18460
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18461
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18462
0
        }
18463
18464
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18465
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18466
0
        {
18467
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18468
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18469
0
        }
18470
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18471
0
        {
18472
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18473
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18474
0
        }
18475
0
        else
18476
0
        {
18477
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18478
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18479
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18480
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18481
0
        }
18482
18483
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18484
0
    }
18485
18486
0
    if (only_write_to_single_node == NULL)
18487
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18488
18489
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18490
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18491
0
    if (child_0_recurse)
18492
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18493
0
    if (child_1_recurse)
18494
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18495
0
}
18496
18497
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18498
0
{
18499
0
    if (node->IsLeafNode())
18500
0
    {
18501
0
        touching_nodes->push_back(node);
18502
0
        return;
18503
0
    }
18504
0
    if (node->ChildNodes[0]->IsVisible)
18505
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18506
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18507
0
    if (node->ChildNodes[1]->IsVisible)
18508
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18509
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18510
0
}
18511
18512
// (Depth-First, Pre-Order)
18513
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18514
0
{
18515
0
    if (node->IsLeafNode())
18516
0
        return;
18517
18518
0
    ImGuiContext& g = *GImGui;
18519
18520
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18521
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18522
0
    if (child_0->IsVisible && child_1->IsVisible)
18523
0
    {
18524
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18525
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18526
0
        IM_ASSERT(axis != ImGuiAxis_None);
18527
0
        ImRect bb;
18528
0
        bb.Min = child_0->Pos;
18529
0
        bb.Max = child_1->Pos;
18530
0
        bb.Min[axis] += child_0->Size[axis];
18531
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18532
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18533
18534
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18535
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18536
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18537
0
        {
18538
0
            ImGuiWindow* window = g.CurrentWindow;
18539
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18540
0
        }
18541
0
        else
18542
0
        {
18543
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18544
            //bb.Max[axis] -= 1;
18545
0
            PushID(node->ID);
18546
18547
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18548
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18549
0
            float min_size = g.Style.WindowMinSize[axis];
18550
0
            float resize_limits[2];
18551
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18552
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18553
18554
0
            ImGuiID splitter_id = GetID("##Splitter");
18555
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18556
0
            {
18557
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18558
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18559
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18560
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18561
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18562
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18563
18564
                // [DEBUG] Render touching nodes & limits
18565
                /*
18566
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18567
                for (int n = 0; n < 2; n++)
18568
                {
18569
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18570
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18571
                    if (axis == ImGuiAxis_X)
18572
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18573
                    else
18574
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18575
                }
18576
                */
18577
0
            }
18578
18579
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18580
0
            float cur_size_0 = child_0->Size[axis];
18581
0
            float cur_size_1 = child_1->Size[axis];
18582
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18583
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18584
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18585
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18586
0
            {
18587
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18588
0
                {
18589
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18590
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18591
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18592
18593
                    // Lock the size of every node that is a sibling of the node we are touching
18594
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18595
0
                    for (int side_n = 0; side_n < 2; side_n++)
18596
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18597
0
                        {
18598
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18599
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18600
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18601
0
                            while (touching_node->ParentNode != node)
18602
0
                            {
18603
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18604
0
                                {
18605
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18606
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18607
0
                                    node_to_preserve->WantLockSizeOnce = true;
18608
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18609
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18610
0
                                }
18611
0
                                touching_node = touching_node->ParentNode;
18612
0
                            }
18613
0
                        }
18614
18615
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18616
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18617
0
                    MarkIniSettingsDirty();
18618
0
                }
18619
0
            }
18620
0
            PopID();
18621
0
        }
18622
0
    }
18623
18624
0
    if (child_0->IsVisible)
18625
0
        DockNodeTreeUpdateSplitter(child_0);
18626
0
    if (child_1->IsVisible)
18627
0
        DockNodeTreeUpdateSplitter(child_1);
18628
0
}
18629
18630
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18631
0
{
18632
0
    if (node->IsLeafNode())
18633
0
        return node;
18634
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18635
0
        return leaf_node;
18636
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18637
0
        return leaf_node;
18638
0
    return NULL;
18639
0
}
18640
18641
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18642
0
{
18643
0
    if (!node->IsVisible)
18644
0
        return NULL;
18645
18646
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18647
0
    ImRect r(node->Pos, node->Pos + node->Size);
18648
0
    r.Expand(dock_spacing * 0.5f);
18649
0
    bool inside = r.Contains(pos);
18650
0
    if (!inside)
18651
0
        return NULL;
18652
18653
0
    if (node->IsLeafNode())
18654
0
        return node;
18655
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18656
0
        return hovered_node;
18657
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18658
0
        return hovered_node;
18659
18660
    // This means we are hovering over the splitter/spacing of a parent node
18661
0
    return node;
18662
0
}
18663
18664
//-----------------------------------------------------------------------------
18665
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18666
//-----------------------------------------------------------------------------
18667
// - SetWindowDock() [Internal]
18668
// - DockSpace()
18669
// - DockSpaceOverViewport()
18670
//-----------------------------------------------------------------------------
18671
18672
// [Internal] Called via SetNextWindowDockID()
18673
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18674
0
{
18675
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18676
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18677
0
        return;
18678
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18679
18680
0
    if (window->DockId == dock_id)
18681
0
        return;
18682
18683
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18684
0
    ImGuiContext& g = *GImGui;
18685
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18686
0
        if (new_node->IsSplitNode())
18687
0
        {
18688
            // Policy: Find central node or latest focused node. We first move back to our root node.
18689
0
            new_node = DockNodeGetRootNode(new_node);
18690
0
            if (new_node->CentralNode)
18691
0
            {
18692
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18693
0
                dock_id = new_node->CentralNode->ID;
18694
0
            }
18695
0
            else
18696
0
            {
18697
0
                dock_id = new_node->LastFocusedNodeId;
18698
0
            }
18699
0
        }
18700
18701
0
    if (window->DockId == dock_id)
18702
0
        return;
18703
18704
0
    if (window->DockNode)
18705
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18706
0
    window->DockId = dock_id;
18707
0
}
18708
18709
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18710
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18711
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18712
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18713
ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18714
0
{
18715
0
    ImGuiContext& g = *GImGui;
18716
0
    ImGuiWindow* window = GetCurrentWindowRead();
18717
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18718
0
        return 0;
18719
18720
    // Early out if parent window is hidden/collapsed
18721
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18722
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18723
0
    if (window->SkipItems)
18724
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18725
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18726
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18727
18728
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18729
0
    IM_ASSERT(dockspace_id != 0);
18730
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
18731
0
    if (node == NULL)
18732
0
    {
18733
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
18734
0
        node = DockContextAddNode(&g, dockspace_id);
18735
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18736
0
    }
18737
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18738
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
18739
0
    node->SharedFlags = flags;
18740
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18741
18742
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18743
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18744
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18745
0
    {
18746
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18747
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18748
0
        return dockspace_id;
18749
0
    }
18750
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18751
18752
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18753
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18754
0
    {
18755
0
        node->LastFrameAlive = g.FrameCount;
18756
0
        return dockspace_id;
18757
0
    }
18758
18759
0
    const ImVec2 content_avail = GetContentRegionAvail();
18760
0
    ImVec2 size = ImTrunc(size_arg);
18761
0
    if (size.x <= 0.0f)
18762
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18763
0
    if (size.y <= 0.0f)
18764
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18765
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18766
18767
0
    node->Pos = window->DC.CursorPos;
18768
0
    node->Size = node->SizeRef = size;
18769
0
    SetNextWindowPos(node->Pos);
18770
0
    SetNextWindowSize(node->Size);
18771
0
    g.NextWindowData.PosUndock = false;
18772
18773
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18774
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18775
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18776
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18777
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18778
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18779
18780
0
    char title[256];
18781
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
18782
18783
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18784
0
    Begin(title, NULL, window_flags);
18785
0
    PopStyleVar();
18786
18787
0
    ImGuiWindow* host_window = g.CurrentWindow;
18788
0
    DockNodeSetupHostWindow(node, host_window);
18789
0
    host_window->ChildId = window->GetID(title);
18790
0
    node->OnlyNodeWithWindows = NULL;
18791
18792
0
    IM_ASSERT(node->IsRootNode());
18793
18794
    // We need to handle the rare case were a central node is missing.
18795
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18796
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18797
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18798
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18799
    // as it doesn't make sense for an empty dockspace to not have this property.
18800
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18801
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18802
18803
    // Update the node
18804
0
    DockNodeUpdate(node);
18805
18806
0
    End();
18807
18808
0
    ImRect bb(node->Pos, node->Pos + size);
18809
0
    ItemSize(size);
18810
0
    ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18811
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18812
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18813
18814
0
    return dockspace_id;
18815
0
}
18816
18817
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18818
// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
18819
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18820
// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18821
ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18822
0
{
18823
0
    if (viewport == NULL)
18824
0
        viewport = GetMainViewport();
18825
18826
    // Submit a window filling the entire viewport
18827
0
    SetNextWindowPos(viewport->WorkPos);
18828
0
    SetNextWindowSize(viewport->WorkSize);
18829
0
    SetNextWindowViewport(viewport->ID);
18830
18831
0
    ImGuiWindowFlags host_window_flags = 0;
18832
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18833
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18834
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18835
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18836
18837
0
    char label[32];
18838
0
    ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
18839
18840
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18841
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18842
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18843
0
    Begin(label, NULL, host_window_flags);
18844
0
    PopStyleVar(3);
18845
18846
    // Submit the dockspace
18847
0
    if (dockspace_id == 0)
18848
0
        dockspace_id = GetID("DockSpace");
18849
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18850
18851
0
    End();
18852
18853
0
    return dockspace_id;
18854
0
}
18855
18856
//-----------------------------------------------------------------------------
18857
// Docking: Builder Functions
18858
//-----------------------------------------------------------------------------
18859
// Very early end-user API to manipulate dock nodes.
18860
// Only available in imgui_internal.h. Expect this API to change/break!
18861
// It is expected that those functions are all called _before_ the dockspace node submission.
18862
//-----------------------------------------------------------------------------
18863
// - DockBuilderDockWindow()
18864
// - DockBuilderGetNode()
18865
// - DockBuilderSetNodePos()
18866
// - DockBuilderSetNodeSize()
18867
// - DockBuilderAddNode()
18868
// - DockBuilderRemoveNode()
18869
// - DockBuilderRemoveNodeChildNodes()
18870
// - DockBuilderRemoveNodeDockedWindows()
18871
// - DockBuilderSplitNode()
18872
// - DockBuilderCopyNodeRec()
18873
// - DockBuilderCopyNode()
18874
// - DockBuilderCopyWindowSettings()
18875
// - DockBuilderCopyDockSpace()
18876
// - DockBuilderFinish()
18877
//-----------------------------------------------------------------------------
18878
18879
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18880
0
{
18881
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18882
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18883
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18884
0
    ImGuiID window_id = ImHashStr(window_name);
18885
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18886
0
    {
18887
        // Apply to created window
18888
0
        ImGuiID prev_node_id = window->DockId;
18889
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18890
0
        if (window->DockId != prev_node_id)
18891
0
            window->DockOrder = -1;
18892
0
    }
18893
0
    else
18894
0
    {
18895
        // Apply to settings
18896
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18897
0
        if (settings == NULL)
18898
0
            settings = CreateNewWindowSettings(window_name);
18899
0
        if (settings->DockId != node_id)
18900
0
            settings->DockOrder = -1;
18901
0
        settings->DockId = node_id;
18902
0
    }
18903
0
}
18904
18905
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18906
0
{
18907
0
    ImGuiContext& g = *GImGui;
18908
0
    return DockContextFindNodeByID(&g, node_id);
18909
0
}
18910
18911
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18912
0
{
18913
0
    ImGuiContext& g = *GImGui;
18914
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18915
0
    if (node == NULL)
18916
0
        return;
18917
0
    node->Pos = pos;
18918
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18919
0
}
18920
18921
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18922
0
{
18923
0
    ImGuiContext& g = *GImGui;
18924
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18925
0
    if (node == NULL)
18926
0
        return;
18927
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18928
0
    node->Size = node->SizeRef = size;
18929
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18930
0
}
18931
18932
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18933
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18934
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18935
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18936
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18937
// - Use (id == 0) to let the system allocate a node identifier.
18938
// - Existing node with a same id will be removed.
18939
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18940
0
{
18941
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18942
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18943
18944
0
    if (node_id != 0)
18945
0
        DockBuilderRemoveNode(node_id);
18946
18947
0
    ImGuiDockNode* node = NULL;
18948
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18949
0
    {
18950
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18951
0
        node = DockContextFindNodeByID(&g, node_id);
18952
0
    }
18953
0
    else
18954
0
    {
18955
0
        node = DockContextAddNode(&g, node_id);
18956
0
        node->SetLocalFlags(flags);
18957
0
    }
18958
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18959
0
    return node->ID;
18960
0
}
18961
18962
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18963
0
{
18964
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18965
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18966
18967
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18968
0
    if (node == NULL)
18969
0
        return;
18970
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18971
0
    DockBuilderRemoveNodeChildNodes(node_id);
18972
    // Node may have moved or deleted if e.g. any merge happened
18973
0
    node = DockContextFindNodeByID(&g, node_id);
18974
0
    if (node == NULL)
18975
0
        return;
18976
0
    if (node->IsCentralNode() && node->ParentNode)
18977
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18978
0
    DockContextRemoveNode(&g, node, true);
18979
0
}
18980
18981
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18982
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18983
0
{
18984
0
    ImGuiContext& g = *GImGui;
18985
0
    ImGuiDockContext* dc = &g.DockContext;
18986
18987
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
18988
0
    if (root_id && root_node == NULL)
18989
0
        return;
18990
0
    bool has_central_node = false;
18991
18992
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18993
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18994
18995
    // Process active windows
18996
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18997
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18998
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18999
0
        {
19000
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
19001
0
            if (want_removal)
19002
0
            {
19003
0
                if (node->IsCentralNode())
19004
0
                    has_central_node = true;
19005
0
                if (root_id != 0)
19006
0
                    DockContextQueueNotifyRemovedNode(&g, node);
19007
0
                if (root_node)
19008
0
                {
19009
0
                    DockNodeMoveWindows(root_node, node);
19010
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
19011
0
                }
19012
0
                nodes_to_remove.push_back(node);
19013
0
            }
19014
0
        }
19015
19016
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
19017
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
19018
0
    if (root_node)
19019
0
    {
19020
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
19021
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
19022
0
    }
19023
19024
    // Apply to settings
19025
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19026
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
19027
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
19028
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
19029
0
                {
19030
0
                    settings->DockId = root_id;
19031
0
                    break;
19032
0
                }
19033
19034
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
19035
0
    if (nodes_to_remove.Size > 1)
19036
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
19037
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
19038
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
19039
19040
0
    if (root_id == 0)
19041
0
    {
19042
0
        dc->Nodes.Clear();
19043
0
        dc->Requests.clear();
19044
0
    }
19045
0
    else if (has_central_node)
19046
0
    {
19047
0
        root_node->CentralNode = root_node;
19048
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19049
0
    }
19050
0
}
19051
19052
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
19053
0
{
19054
    // Clear references in settings
19055
0
    ImGuiContext& g = *GImGui;
19056
0
    if (clear_settings_refs)
19057
0
    {
19058
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19059
0
        {
19060
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
19061
0
            if (!want_removal && settings->DockId != 0)
19062
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
19063
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
19064
0
                        want_removal = true;
19065
0
            if (want_removal)
19066
0
                settings->DockId = 0;
19067
0
        }
19068
0
    }
19069
19070
    // Clear references in windows
19071
0
    for (int n = 0; n < g.Windows.Size; n++)
19072
0
    {
19073
0
        ImGuiWindow* window = g.Windows[n];
19074
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
19075
0
        if (want_removal)
19076
0
        {
19077
0
            const ImGuiID backup_dock_id = window->DockId;
19078
0
            IM_UNUSED(backup_dock_id);
19079
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
19080
0
            if (!clear_settings_refs)
19081
0
                IM_ASSERT(window->DockId == backup_dock_id);
19082
0
        }
19083
0
    }
19084
0
}
19085
19086
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
19087
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
19088
// FIXME-DOCK: We are not exposing nor using split_outer.
19089
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
19090
0
{
19091
0
    ImGuiContext& g = *GImGui;
19092
0
    IM_ASSERT(split_dir != ImGuiDir_None);
19093
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
19094
19095
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
19096
0
    if (node == NULL)
19097
0
    {
19098
0
        IM_ASSERT(node != NULL);
19099
0
        return 0;
19100
0
    }
19101
19102
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
19103
19104
0
    ImGuiDockRequest req;
19105
0
    req.Type = ImGuiDockRequestType_Split;
19106
0
    req.DockTargetWindow = NULL;
19107
0
    req.DockTargetNode = node;
19108
0
    req.DockPayload = NULL;
19109
0
    req.DockSplitDir = split_dir;
19110
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
19111
0
    req.DockSplitOuter = false;
19112
0
    DockContextProcessDock(&g, &req);
19113
19114
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
19115
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
19116
0
    if (out_id_at_dir)
19117
0
        *out_id_at_dir = id_at_dir;
19118
0
    if (out_id_at_opposite_dir)
19119
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
19120
0
    return id_at_dir;
19121
0
}
19122
19123
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
19124
0
{
19125
0
    ImGuiContext& g = *GImGui;
19126
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
19127
0
    dst_node->SharedFlags = src_node->SharedFlags;
19128
0
    dst_node->LocalFlags = src_node->LocalFlags;
19129
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
19130
0
    dst_node->Pos = src_node->Pos;
19131
0
    dst_node->Size = src_node->Size;
19132
0
    dst_node->SizeRef = src_node->SizeRef;
19133
0
    dst_node->SplitAxis = src_node->SplitAxis;
19134
0
    dst_node->UpdateMergedFlags();
19135
19136
0
    out_node_remap_pairs->push_back(src_node->ID);
19137
0
    out_node_remap_pairs->push_back(dst_node->ID);
19138
19139
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
19140
0
        if (src_node->ChildNodes[child_n])
19141
0
        {
19142
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
19143
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
19144
0
        }
19145
19146
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
19147
0
    return dst_node;
19148
0
}
19149
19150
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
19151
0
{
19152
0
    ImGuiContext& g = *GImGui;
19153
0
    IM_ASSERT(src_node_id != 0);
19154
0
    IM_ASSERT(dst_node_id != 0);
19155
0
    IM_ASSERT(out_node_remap_pairs != NULL);
19156
19157
0
    DockBuilderRemoveNode(dst_node_id);
19158
19159
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
19160
0
    IM_ASSERT(src_node != NULL);
19161
19162
0
    out_node_remap_pairs->clear();
19163
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
19164
19165
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
19166
0
}
19167
19168
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
19169
0
{
19170
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
19171
0
    if (src_window == NULL)
19172
0
        return;
19173
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
19174
0
    {
19175
0
        dst_window->Pos = src_window->Pos;
19176
0
        dst_window->Size = src_window->Size;
19177
0
        dst_window->SizeFull = src_window->SizeFull;
19178
0
        dst_window->Collapsed = src_window->Collapsed;
19179
0
    }
19180
0
    else
19181
0
    {
19182
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
19183
0
        if (!dst_settings)
19184
0
            dst_settings = CreateNewWindowSettings(dst_name);
19185
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
19186
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
19187
0
        {
19188
0
            dst_settings->ViewportPos = window_pos_2ih;
19189
0
            dst_settings->ViewportId = src_window->ViewportId;
19190
0
            dst_settings->Pos = ImVec2ih(0, 0);
19191
0
        }
19192
0
        else
19193
0
        {
19194
0
            dst_settings->Pos = window_pos_2ih;
19195
0
        }
19196
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
19197
0
        dst_settings->Collapsed = src_window->Collapsed;
19198
0
    }
19199
0
}
19200
19201
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
19202
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
19203
0
{
19204
0
    ImGuiContext& g = *GImGui;
19205
0
    IM_ASSERT(src_dockspace_id != 0);
19206
0
    IM_ASSERT(dst_dockspace_id != 0);
19207
0
    IM_ASSERT(in_window_remap_pairs != NULL);
19208
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
19209
19210
    // Duplicate entire dock
19211
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
19212
    // whereas we could attempt to at least keep them together in a new, same floating node.
19213
0
    ImVector<ImGuiID> node_remap_pairs;
19214
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
19215
19216
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
19217
    // (The windows associated to src_dockspace_id are staying in place)
19218
0
    ImVector<ImGuiID> src_windows;
19219
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
19220
0
    {
19221
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
19222
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
19223
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
19224
0
        src_windows.push_back(src_window_id);
19225
19226
        // Search in the remapping tables
19227
0
        ImGuiID src_dock_id = 0;
19228
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
19229
0
            src_dock_id = src_window->DockId;
19230
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
19231
0
            src_dock_id = src_window_settings->DockId;
19232
0
        ImGuiID dst_dock_id = 0;
19233
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19234
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
19235
0
            {
19236
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19237
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
19238
0
                break;
19239
0
            }
19240
19241
0
        if (dst_dock_id != 0)
19242
0
        {
19243
            // Docked windows gets redocked into the new node hierarchy.
19244
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
19245
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
19246
0
        }
19247
0
        else
19248
0
        {
19249
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
19250
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
19251
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
19252
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
19253
0
        }
19254
0
    }
19255
19256
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
19257
    // Find those windows and move to them to the cloned dock node. This may be optional?
19258
    // Dock those are a second step as undocking would invalidate source dock nodes.
19259
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
19260
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
19261
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19262
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
19263
0
        {
19264
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19265
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
19266
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19267
0
            {
19268
0
                ImGuiWindow* window = node->Windows[window_n];
19269
0
                if (src_windows.contains(window->ID))
19270
0
                    continue;
19271
19272
                // Docked windows gets redocked into the new node hierarchy.
19273
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
19274
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
19275
0
            }
19276
0
        }
19277
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
19278
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
19279
0
}
19280
19281
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
19282
void ImGui::DockBuilderFinish(ImGuiID root_id)
19283
0
{
19284
0
    ImGuiContext& g = *GImGui;
19285
    //DockContextRebuild(&g);
19286
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
19287
0
}
19288
19289
//-----------------------------------------------------------------------------
19290
// Docking: Begin/End Support Functions (called from Begin/End)
19291
//-----------------------------------------------------------------------------
19292
// - GetWindowAlwaysWantOwnTabBar()
19293
// - DockContextBindNodeToWindow()
19294
// - BeginDocked()
19295
// - BeginDockableDragDropSource()
19296
// - BeginDockableDragDropTarget()
19297
//-----------------------------------------------------------------------------
19298
19299
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
19300
300k
{
19301
300k
    ImGuiContext& g = *GImGui;
19302
300k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
19303
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
19304
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
19305
0
                return true;
19306
300k
    return false;
19307
300k
}
19308
19309
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
19310
0
{
19311
0
    ImGuiContext& g = *ctx;
19312
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
19313
0
    IM_ASSERT(window->DockNode == NULL);
19314
19315
    // We should not be docking into a split node (SetWindowDock should avoid this)
19316
0
    if (node && node->IsSplitNode())
19317
0
    {
19318
0
        DockContextProcessUndockWindow(ctx, window);
19319
0
        return NULL;
19320
0
    }
19321
19322
    // Create node
19323
0
    if (node == NULL)
19324
0
    {
19325
0
        node = DockContextAddNode(ctx, window->DockId);
19326
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19327
0
        node->LastFrameAlive = g.FrameCount;
19328
0
    }
19329
19330
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19331
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19332
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19333
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19334
0
    if (!node->IsVisible)
19335
0
    {
19336
0
        ImGuiDockNode* ancestor_node = node;
19337
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19338
0
            ancestor_node = ancestor_node->ParentNode;
19339
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19340
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19341
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19342
0
    }
19343
19344
    // Add window to node
19345
0
    bool node_was_visible = node->IsVisible;
19346
0
    DockNodeAddWindow(node, window, true);
19347
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19348
0
    IM_ASSERT(node == window->DockNode);
19349
0
    return node;
19350
0
}
19351
19352
static void StoreDockStyleForWindow(ImGuiWindow* window)
19353
95
{
19354
95
    ImGuiContext& g = *GImGui;
19355
855
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19356
760
        window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19357
95
}
19358
19359
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19360
0
{
19361
0
    ImGuiContext& g = *GImGui;
19362
19363
    // Clear fields ahead so most early-out paths don't have to do it
19364
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19365
19366
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19367
0
    if (auto_dock_node)
19368
0
    {
19369
0
        if (window->DockId == 0)
19370
0
        {
19371
0
            IM_ASSERT(window->DockNode == NULL);
19372
0
            window->DockId = DockContextGenNodeID(&g);
19373
0
        }
19374
0
    }
19375
0
    else
19376
0
    {
19377
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19378
0
        bool want_undock = false;
19379
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19380
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19381
0
        if (want_undock)
19382
0
        {
19383
0
            DockContextProcessUndockWindow(&g, window);
19384
0
            return;
19385
0
        }
19386
0
    }
19387
19388
    // Bind to our dock node
19389
0
    ImGuiDockNode* node = window->DockNode;
19390
0
    if (node != NULL)
19391
0
        IM_ASSERT(window->DockId == node->ID);
19392
0
    if (window->DockId != 0 && node == NULL)
19393
0
    {
19394
0
        node = DockContextBindNodeToWindow(&g, window);
19395
0
        if (node == NULL)
19396
0
            return;
19397
0
    }
19398
19399
#if 0
19400
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19401
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19402
    {
19403
        DockContextProcessUndockWindow(ctx, window);
19404
        return;
19405
    }
19406
#endif
19407
19408
    // Undock if our dockspace node disappeared
19409
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19410
0
    if (node->LastFrameAlive < g.FrameCount)
19411
0
    {
19412
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19413
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19414
0
        if (root_node->LastFrameAlive < g.FrameCount)
19415
0
            DockContextProcessUndockWindow(&g, window);
19416
0
        else
19417
0
            window->DockIsActive = true;
19418
0
        return;
19419
0
    }
19420
19421
    // Store style overrides
19422
0
    StoreDockStyleForWindow(window);
19423
19424
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19425
    // and never create neither a host window neither a tab bar.
19426
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19427
0
    if (node->HostWindow == NULL)
19428
0
    {
19429
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19430
0
            window->DockIsActive = true;
19431
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19432
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19433
0
        return;
19434
0
    }
19435
19436
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19437
0
    IM_ASSERT(node->HostWindow);
19438
0
    IM_ASSERT(node->IsLeafNode());
19439
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19440
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19441
19442
    // Undock if we are submitted earlier than the host window
19443
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19444
0
    {
19445
0
        DockContextProcessUndockWindow(&g, window);
19446
0
        return;
19447
0
    }
19448
19449
    // Position/Size window
19450
0
    SetNextWindowPos(node->Pos);
19451
0
    SetNextWindowSize(node->Size);
19452
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19453
0
    window->DockIsActive = true;
19454
0
    window->DockNodeIsVisible = true;
19455
0
    window->DockTabIsVisible = false;
19456
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19457
0
        return;
19458
19459
    // When the window is selected we mark it as visible.
19460
0
    if (node->VisibleWindow == window)
19461
0
        window->DockTabIsVisible = true;
19462
19463
    // Update window flag
19464
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19465
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19466
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19467
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19468
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19469
0
    else
19470
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19471
19472
    // Save new dock order only if the window has been visible once already
19473
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19474
0
    if (node->TabBar && window->WasActive)
19475
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19476
19477
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19478
0
        *p_open = false;
19479
19480
    // Update ChildId to allow returning from Child to Parent with Escape
19481
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19482
0
    window->ChildId = parent_window->GetID(window->Name);
19483
0
}
19484
19485
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19486
144
{
19487
144
    ImGuiContext& g = *GImGui;
19488
144
    IM_ASSERT(g.ActiveId == window->MoveId);
19489
144
    IM_ASSERT(g.MovingWindow == window);
19490
144
    IM_ASSERT(g.CurrentWindow == window);
19491
19492
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19493
144
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19494
0
    {
19495
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19496
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19497
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19498
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19499
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19500
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19501
0
        return;
19502
0
    }
19503
19504
144
    g.LastItemData.ID = window->MoveId;
19505
144
    window = window->RootWindowDockTree;
19506
144
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19507
144
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19508
144
    ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
19509
144
    if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
19510
95
    {
19511
95
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19512
95
        EndDragDropSource();
19513
95
        StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
19514
95
    }
19515
144
}
19516
19517
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19518
101
{
19519
101
    ImGuiContext& g = *GImGui;
19520
19521
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19522
101
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19523
101
    if (!g.DragDropActive)
19524
0
        return;
19525
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19526
101
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19527
99
        return;
19528
19529
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19530
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19531
2
    const ImGuiPayload* payload = &g.DragDropPayload;
19532
2
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19533
0
    {
19534
0
        EndDragDropTarget();
19535
0
        return;
19536
0
    }
19537
19538
2
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19539
2
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19540
2
    {
19541
        // Select target node
19542
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19543
2
        bool dock_into_floating_window = false;
19544
2
        ImGuiDockNode* node = NULL;
19545
2
        if (window->DockNodeAsHost)
19546
0
        {
19547
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19548
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19549
19550
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19551
            // In this case we need to fallback into any leaf mode, possibly the central node.
19552
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19553
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19554
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19555
0
        }
19556
2
        else
19557
2
        {
19558
2
            if (window->DockNode)
19559
0
                node = window->DockNode;
19560
2
            else
19561
2
                dock_into_floating_window = true; // Dock into a regular window
19562
2
        }
19563
19564
2
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19565
2
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19566
19567
        // Preview docking request and find out split direction/ratio
19568
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19569
2
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19570
2
        if (do_preview && (node != NULL || dock_into_floating_window))
19571
0
        {
19572
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19573
0
            ImGuiDockPreviewData split_inner;
19574
0
            ImGuiDockPreviewData split_outer;
19575
0
            ImGuiDockPreviewData* split_data = &split_inner;
19576
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19577
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19578
0
                {
19579
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19580
0
                    if (split_outer.IsSplitDirExplicit)
19581
0
                        split_data = &split_outer;
19582
0
                }
19583
0
            if (!node || node->IsLeafNode())
19584
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19585
0
            if (split_data == &split_outer)
19586
0
                split_inner.IsDropAllowed = false;
19587
19588
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19589
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19590
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19591
19592
            // Queue docking request
19593
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19594
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19595
0
        }
19596
2
    }
19597
2
    EndDragDropTarget();
19598
2
}
19599
19600
//-----------------------------------------------------------------------------
19601
// Docking: Settings
19602
//-----------------------------------------------------------------------------
19603
// - DockSettingsRenameNodeReferences()
19604
// - DockSettingsRemoveNodeReferences()
19605
// - DockSettingsFindNodeSettings()
19606
// - DockSettingsHandler_ApplyAll()
19607
// - DockSettingsHandler_ReadOpen()
19608
// - DockSettingsHandler_ReadLine()
19609
// - DockSettingsHandler_DockNodeToSettings()
19610
// - DockSettingsHandler_WriteAll()
19611
//-----------------------------------------------------------------------------
19612
19613
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19614
0
{
19615
0
    ImGuiContext& g = *GImGui;
19616
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19617
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19618
0
    {
19619
0
        ImGuiWindow* window = g.Windows[window_n];
19620
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19621
0
            window->DockId = new_node_id;
19622
0
    }
19623
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19624
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19625
0
        if (settings->DockId == old_node_id)
19626
0
            settings->DockId = new_node_id;
19627
0
}
19628
19629
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19630
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19631
0
{
19632
0
    ImGuiContext& g = *GImGui;
19633
0
    int found = 0;
19634
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19635
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19636
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19637
0
            if (settings->DockId == node_ids[node_n])
19638
0
            {
19639
0
                settings->DockId = 0;
19640
0
                settings->DockOrder = -1;
19641
0
                if (++found < node_ids_count)
19642
0
                    break;
19643
0
                return;
19644
0
            }
19645
0
}
19646
19647
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19648
0
{
19649
    // FIXME-OPT
19650
0
    ImGuiDockContext* dc = &ctx->DockContext;
19651
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19652
0
        if (dc->NodesSettings[n].ID == id)
19653
0
            return &dc->NodesSettings[n];
19654
0
    return NULL;
19655
0
}
19656
19657
// Clear settings data
19658
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19659
0
{
19660
0
    ImGuiDockContext* dc = &ctx->DockContext;
19661
0
    dc->NodesSettings.clear();
19662
0
    DockContextClearNodes(ctx, 0, true);
19663
0
}
19664
19665
// Recreate nodes based on settings data
19666
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19667
0
{
19668
    // Prune settings at boot time only
19669
0
    ImGuiDockContext* dc = &ctx->DockContext;
19670
0
    if (ctx->Windows.Size == 0)
19671
0
        DockContextPruneUnusedSettingsNodes(ctx);
19672
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19673
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19674
0
}
19675
19676
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19677
0
{
19678
0
    if (strcmp(name, "Data") != 0)
19679
0
        return NULL;
19680
0
    return (void*)1;
19681
0
}
19682
19683
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19684
0
{
19685
0
    char c = 0;
19686
0
    int x = 0, y = 0;
19687
0
    int r = 0;
19688
19689
    // Parsing, e.g.
19690
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19691
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19692
    // Important: this code expect currently fields in a fixed order.
19693
0
    ImGuiDockNodeSettings node;
19694
0
    line = ImStrSkipBlank(line);
19695
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19696
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19697
0
    else return;
19698
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19699
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19700
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19701
0
    if (node.ParentNodeId == 0)
19702
0
    {
19703
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19704
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19705
0
    }
19706
0
    else
19707
0
    {
19708
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19709
0
    }
19710
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19711
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19712
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19713
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19714
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19715
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19716
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19717
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19718
0
    if (node.ParentNodeId != 0)
19719
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19720
0
            node.Depth = parent_settings->Depth + 1;
19721
0
    ctx->DockContext.NodesSettings.push_back(node);
19722
0
}
19723
19724
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19725
0
{
19726
0
    ImGuiDockNodeSettings node_settings;
19727
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19728
0
    node_settings.ID = node->ID;
19729
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19730
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19731
0
    node_settings.SelectedTabId = node->SelectedTabId;
19732
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19733
0
    node_settings.Depth = (char)depth;
19734
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19735
0
    node_settings.Pos = ImVec2ih(node->Pos);
19736
0
    node_settings.Size = ImVec2ih(node->Size);
19737
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19738
0
    dc->NodesSettings.push_back(node_settings);
19739
0
    if (node->ChildNodes[0])
19740
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19741
0
    if (node->ChildNodes[1])
19742
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19743
0
}
19744
19745
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19746
0
{
19747
0
    ImGuiContext& g = *ctx;
19748
0
    ImGuiDockContext* dc = &ctx->DockContext;
19749
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19750
0
        return;
19751
19752
    // Gather settings data
19753
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19754
0
    dc->NodesSettings.resize(0);
19755
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19756
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19757
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19758
0
            if (node->IsRootNode())
19759
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19760
19761
0
    int max_depth = 0;
19762
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19763
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19764
19765
    // Write to text buffer
19766
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19767
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19768
0
    {
19769
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19770
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19771
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19772
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19773
0
        if (node_settings->ParentNodeId)
19774
0
        {
19775
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19776
0
        }
19777
0
        else
19778
0
        {
19779
0
            if (node_settings->ParentWindowId)
19780
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19781
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19782
0
        }
19783
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19784
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19785
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19786
0
            buf->appendf(" NoResize=1");
19787
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19788
0
            buf->appendf(" CentralNode=1");
19789
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19790
0
            buf->appendf(" NoTabBar=1");
19791
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19792
0
            buf->appendf(" HiddenTabBar=1");
19793
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19794
0
            buf->appendf(" NoWindowMenuButton=1");
19795
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19796
0
            buf->appendf(" NoCloseButton=1");
19797
0
        if (node_settings->SelectedTabId)
19798
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19799
19800
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19801
0
        if (g.IO.ConfigDebugIniSettings)
19802
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19803
0
            {
19804
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19805
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19806
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19807
                // Iterate settings so we can give info about windows that didn't exist during the session.
19808
0
                int contains_window = 0;
19809
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19810
0
                    if (settings->DockId == node_settings->ID)
19811
0
                    {
19812
0
                        if (contains_window++ == 0)
19813
0
                            buf->appendf(" ; contains ");
19814
0
                        buf->appendf("'%s' ", settings->GetName());
19815
0
                    }
19816
0
            }
19817
19818
0
        buf->appendf("\n");
19819
0
    }
19820
0
    buf->appendf("\n");
19821
0
}
19822
19823
19824
//-----------------------------------------------------------------------------
19825
// [SECTION] PLATFORM DEPENDENT HELPERS
19826
//-----------------------------------------------------------------------------
19827
19828
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19829
19830
#ifdef _MSC_VER
19831
#pragma comment(lib, "user32")
19832
#pragma comment(lib, "kernel32")
19833
#endif
19834
19835
// Win32 clipboard implementation
19836
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19837
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19838
{
19839
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19840
    g.ClipboardHandlerData.clear();
19841
    if (!::OpenClipboard(NULL))
19842
        return NULL;
19843
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19844
    if (wbuf_handle == NULL)
19845
    {
19846
        ::CloseClipboard();
19847
        return NULL;
19848
    }
19849
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19850
    {
19851
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19852
        g.ClipboardHandlerData.resize(buf_len);
19853
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19854
    }
19855
    ::GlobalUnlock(wbuf_handle);
19856
    ::CloseClipboard();
19857
    return g.ClipboardHandlerData.Data;
19858
}
19859
19860
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19861
{
19862
    if (!::OpenClipboard(NULL))
19863
        return;
19864
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19865
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19866
    if (wbuf_handle == NULL)
19867
    {
19868
        ::CloseClipboard();
19869
        return;
19870
    }
19871
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19872
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19873
    ::GlobalUnlock(wbuf_handle);
19874
    ::EmptyClipboard();
19875
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19876
        ::GlobalFree(wbuf_handle);
19877
    ::CloseClipboard();
19878
}
19879
19880
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19881
19882
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19883
static PasteboardRef main_clipboard = 0;
19884
19885
// OSX clipboard implementation
19886
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19887
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19888
{
19889
    if (!main_clipboard)
19890
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19891
    PasteboardClear(main_clipboard);
19892
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19893
    if (cf_data)
19894
    {
19895
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19896
        CFRelease(cf_data);
19897
    }
19898
}
19899
19900
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19901
{
19902
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19903
    if (!main_clipboard)
19904
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19905
    PasteboardSynchronize(main_clipboard);
19906
19907
    ItemCount item_count = 0;
19908
    PasteboardGetItemCount(main_clipboard, &item_count);
19909
    for (ItemCount i = 0; i < item_count; i++)
19910
    {
19911
        PasteboardItemID item_id = 0;
19912
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19913
        CFArrayRef flavor_type_array = 0;
19914
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19915
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19916
        {
19917
            CFDataRef cf_data;
19918
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19919
            {
19920
                g.ClipboardHandlerData.clear();
19921
                int length = (int)CFDataGetLength(cf_data);
19922
                g.ClipboardHandlerData.resize(length + 1);
19923
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19924
                g.ClipboardHandlerData[length] = 0;
19925
                CFRelease(cf_data);
19926
                return g.ClipboardHandlerData.Data;
19927
            }
19928
        }
19929
    }
19930
    return NULL;
19931
}
19932
19933
#else
19934
19935
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19936
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19937
0
{
19938
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19939
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19940
0
}
19941
19942
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19943
0
{
19944
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19945
0
    g.ClipboardHandlerData.clear();
19946
0
    const char* text_end = text + strlen(text);
19947
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19948
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19949
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19950
0
}
19951
19952
#endif
19953
19954
// Win32 API IME support (for Asian languages, etc.)
19955
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19956
19957
#include <imm.h>
19958
#ifdef _MSC_VER
19959
#pragma comment(lib, "imm32")
19960
#endif
19961
19962
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19963
{
19964
    // Notify OS Input Method Editor of text input position
19965
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19966
    if (hwnd == 0)
19967
        return;
19968
19969
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19970
    if (HIMC himc = ::ImmGetContext(hwnd))
19971
    {
19972
        COMPOSITIONFORM composition_form = {};
19973
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19974
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19975
        composition_form.dwStyle = CFS_FORCE_POSITION;
19976
        ::ImmSetCompositionWindow(himc, &composition_form);
19977
        CANDIDATEFORM candidate_form = {};
19978
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19979
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19980
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19981
        ::ImmSetCandidateWindow(himc, &candidate_form);
19982
        ::ImmReleaseContext(hwnd, himc);
19983
    }
19984
}
19985
19986
#else
19987
19988
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19989
19990
#endif
19991
19992
//-----------------------------------------------------------------------------
19993
// [SECTION] METRICS/DEBUGGER WINDOW
19994
//-----------------------------------------------------------------------------
19995
// - DebugRenderViewportThumbnail() [Internal]
19996
// - RenderViewportsThumbnails() [Internal]
19997
// - DebugTextEncoding()
19998
// - MetricsHelpMarker() [Internal]
19999
// - ShowFontAtlas() [Internal]
20000
// - ShowMetricsWindow()
20001
// - DebugNodeColumns() [Internal]
20002
// - DebugNodeDockNode() [Internal]
20003
// - DebugNodeDrawList() [Internal]
20004
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
20005
// - DebugNodeFont() [Internal]
20006
// - DebugNodeFontGlyph() [Internal]
20007
// - DebugNodeStorage() [Internal]
20008
// - DebugNodeTabBar() [Internal]
20009
// - DebugNodeViewport() [Internal]
20010
// - DebugNodeWindow() [Internal]
20011
// - DebugNodeWindowSettings() [Internal]
20012
// - DebugNodeWindowsList() [Internal]
20013
// - DebugNodeWindowsListByBeginStackParent() [Internal]
20014
//-----------------------------------------------------------------------------
20015
20016
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
20017
20018
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
20019
0
{
20020
0
    ImGuiContext& g = *GImGui;
20021
0
    ImGuiWindow* window = g.CurrentWindow;
20022
20023
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
20024
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
20025
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
20026
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
20027
0
    for (ImGuiWindow* thumb_window : g.Windows)
20028
0
    {
20029
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
20030
0
            continue;
20031
0
        if (thumb_window->Viewport != viewport)
20032
0
            continue;
20033
20034
0
        ImRect thumb_r = thumb_window->Rect();
20035
0
        ImRect title_r = thumb_window->TitleBarRect();
20036
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
20037
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
20038
0
        thumb_r.ClipWithFull(bb);
20039
0
        title_r.ClipWithFull(bb);
20040
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
20041
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
20042
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
20043
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20044
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
20045
0
    }
20046
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20047
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
20048
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
20049
0
}
20050
20051
static void RenderViewportsThumbnails()
20052
0
{
20053
0
    ImGuiContext& g = *GImGui;
20054
0
    ImGuiWindow* window = g.CurrentWindow;
20055
20056
    // Draw monitor and calculate their boundaries
20057
0
    float SCALE = 1.0f / 8.0f;
20058
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20059
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20060
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
20061
0
    ImVec2 p = window->DC.CursorPos;
20062
0
    ImVec2 off = p - bb_full.Min * SCALE;
20063
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20064
0
    {
20065
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
20066
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
20067
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
20068
0
    }
20069
20070
    // Draw viewports
20071
0
    for (ImGuiViewportP* viewport : g.Viewports)
20072
0
    {
20073
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
20074
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
20075
0
    }
20076
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
20077
0
}
20078
20079
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
20080
0
{
20081
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
20082
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
20083
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
20084
0
}
20085
20086
// Draw an arbitrary US keyboard layout to visualize translated keys
20087
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
20088
0
{
20089
0
    const float scale = ImGui::GetFontSize() / 13.0f;
20090
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
20091
0
    const float  key_rounding = 3.0f * scale;
20092
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
20093
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
20094
0
    const float  key_face_rounding = 2.0f * scale;
20095
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
20096
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
20097
0
    const float  key_row_offset = 9.0f * scale;
20098
20099
0
    ImVec2 board_min = GetCursorScreenPos();
20100
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
20101
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
20102
20103
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
20104
0
    const KeyLayoutData keys_to_display[] =
20105
0
    {
20106
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
20107
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
20108
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
20109
0
    };
20110
20111
    // Elements rendered manually via ImDrawList API are not clipped automatically.
20112
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
20113
0
    Dummy(board_max - board_min);
20114
0
    if (!IsItemVisible())
20115
0
        return;
20116
0
    draw_list->PushClipRect(board_min, board_max, true);
20117
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
20118
0
    {
20119
0
        const KeyLayoutData* key_data = &keys_to_display[n];
20120
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
20121
0
        ImVec2 key_max = key_min + key_size;
20122
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
20123
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
20124
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
20125
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
20126
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
20127
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
20128
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
20129
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
20130
0
        if (IsKeyDown(key_data->Key))
20131
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
20132
0
    }
20133
0
    draw_list->PopClipRect();
20134
0
}
20135
20136
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
20137
void ImGui::DebugTextEncoding(const char* str)
20138
0
{
20139
0
    Text("Text: \"%s\"", str);
20140
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
20141
0
        return;
20142
0
    TableSetupColumn("Offset");
20143
0
    TableSetupColumn("UTF-8");
20144
0
    TableSetupColumn("Glyph");
20145
0
    TableSetupColumn("Codepoint");
20146
0
    TableHeadersRow();
20147
0
    for (const char* p = str; *p != 0; )
20148
0
    {
20149
0
        unsigned int c;
20150
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
20151
0
        TableNextColumn();
20152
0
        Text("%d", (int)(p - str));
20153
0
        TableNextColumn();
20154
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
20155
0
        {
20156
0
            if (byte_index > 0)
20157
0
                SameLine();
20158
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
20159
0
        }
20160
0
        TableNextColumn();
20161
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
20162
0
            TextUnformatted(p, p + c_utf8_len);
20163
0
        else
20164
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
20165
0
        TableNextColumn();
20166
0
        Text("U+%04X", (int)c);
20167
0
        p += c_utf8_len;
20168
0
    }
20169
0
    EndTable();
20170
0
}
20171
20172
static void DebugFlashStyleColorStop()
20173
0
{
20174
0
    ImGuiContext& g = *GImGui;
20175
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
20176
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
20177
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
20178
0
}
20179
20180
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
20181
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
20182
0
{
20183
0
    ImGuiContext& g = *GImGui;
20184
0
    DebugFlashStyleColorStop();
20185
0
    g.DebugFlashStyleColorTime = 0.5f;
20186
0
    g.DebugFlashStyleColorIdx = idx;
20187
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
20188
0
}
20189
20190
void ImGui::UpdateDebugToolFlashStyleColor()
20191
138k
{
20192
138k
    ImGuiContext& g = *GImGui;
20193
138k
    if (g.DebugFlashStyleColorTime <= 0.0f)
20194
138k
        return;
20195
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
20196
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
20197
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
20198
0
        DebugFlashStyleColorStop();
20199
0
}
20200
20201
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
20202
static void MetricsHelpMarker(const char* desc)
20203
0
{
20204
0
    ImGui::TextDisabled("(?)");
20205
0
    if (ImGui::BeginItemTooltip())
20206
0
    {
20207
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
20208
0
        ImGui::TextUnformatted(desc);
20209
0
        ImGui::PopTextWrapPos();
20210
0
        ImGui::EndTooltip();
20211
0
    }
20212
0
}
20213
20214
// [DEBUG] List fonts in a font atlas and display its texture
20215
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
20216
0
{
20217
0
    for (ImFont* font : atlas->Fonts)
20218
0
    {
20219
0
        PushID(font);
20220
0
        DebugNodeFont(font);
20221
0
        PopID();
20222
0
    }
20223
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
20224
0
    {
20225
0
        ImGuiContext& g = *GImGui;
20226
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20227
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
20228
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
20229
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
20230
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
20231
0
        TreePop();
20232
0
    }
20233
0
}
20234
20235
void ImGui::ShowMetricsWindow(bool* p_open)
20236
0
{
20237
0
    ImGuiContext& g = *GImGui;
20238
0
    ImGuiIO& io = g.IO;
20239
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20240
0
    if (cfg->ShowDebugLog)
20241
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
20242
0
    if (cfg->ShowIDStackTool)
20243
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
20244
20245
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
20246
0
    {
20247
0
        End();
20248
0
        return;
20249
0
    }
20250
20251
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
20252
0
    DebugBreakClearData();
20253
20254
    // Basic info
20255
0
    Text("Dear ImGui %s", GetVersion());
20256
0
    if (g.ContextName[0] != 0)
20257
0
    {
20258
0
        SameLine();
20259
0
        Text("(Context Name: \"%s\")", g.ContextName);
20260
0
    }
20261
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
20262
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
20263
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
20264
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
20265
20266
0
    Separator();
20267
20268
    // Debugging enums
20269
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
20270
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
20271
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
20272
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
20273
0
    if (cfg->ShowWindowsRectsType < 0)
20274
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
20275
0
    if (cfg->ShowTablesRectsType < 0)
20276
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
20277
20278
0
    struct Funcs
20279
0
    {
20280
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
20281
0
        {
20282
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
20283
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
20284
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
20285
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
20286
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
20287
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
20288
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
20289
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
20290
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
20291
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
20292
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
20293
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
20294
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
20295
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
20296
0
            IM_ASSERT(0);
20297
0
            return ImRect();
20298
0
        }
20299
20300
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
20301
0
        {
20302
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
20303
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
20304
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
20305
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
20306
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
20307
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
20308
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
20309
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
20310
0
            IM_ASSERT(0);
20311
0
            return ImRect();
20312
0
        }
20313
0
    };
20314
20315
    // Tools
20316
0
    if (TreeNode("Tools"))
20317
0
    {
20318
        // Debug Break features
20319
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
20320
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
20321
0
        SameLine();
20322
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
20323
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
20324
0
            DebugStartItemPicker();
20325
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
20326
20327
0
        SeparatorText("Visualize");
20328
20329
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20330
0
        SameLine();
20331
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20332
20333
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20334
0
        SameLine();
20335
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20336
20337
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20338
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20339
0
        SameLine();
20340
0
        SetNextItemWidth(GetFontSize() * 12);
20341
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20342
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20343
0
        {
20344
0
            BulletText("'%s':", g.NavWindow->Name);
20345
0
            Indent();
20346
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20347
0
            {
20348
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20349
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20350
0
            }
20351
0
            Unindent();
20352
0
        }
20353
20354
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20355
0
        SameLine();
20356
0
        SetNextItemWidth(GetFontSize() * 12);
20357
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20358
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20359
0
        {
20360
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20361
0
            {
20362
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20363
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20364
0
                    continue;
20365
20366
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20367
0
                if (IsItemHovered())
20368
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20369
0
                Indent();
20370
0
                char buf[128];
20371
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20372
0
                {
20373
0
                    if (rect_n >= TRT_ColumnsRect)
20374
0
                    {
20375
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20376
0
                            continue;
20377
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20378
0
                        {
20379
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20380
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20381
0
                            Selectable(buf);
20382
0
                            if (IsItemHovered())
20383
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20384
0
                        }
20385
0
                    }
20386
0
                    else
20387
0
                    {
20388
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20389
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20390
0
                        Selectable(buf);
20391
0
                        if (IsItemHovered())
20392
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20393
0
                    }
20394
0
                }
20395
0
                Unindent();
20396
0
            }
20397
0
        }
20398
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20399
20400
0
        SeparatorText("Validate");
20401
20402
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20403
0
        SameLine();
20404
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20405
20406
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20407
0
        SameLine();
20408
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20409
0
        if (cfg->ShowTextEncodingViewer)
20410
0
        {
20411
0
            static char buf[64] = "";
20412
0
            SetNextItemWidth(-FLT_MIN);
20413
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20414
0
            if (buf[0] != 0)
20415
0
                DebugTextEncoding(buf);
20416
0
        }
20417
20418
0
        TreePop();
20419
0
    }
20420
20421
    // Windows
20422
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20423
0
    {
20424
        //SetNextItemOpen(true, ImGuiCond_Once);
20425
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20426
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20427
0
        if (TreeNode("By submission order (begin stack)"))
20428
0
        {
20429
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20430
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20431
0
            temp_buffer.resize(0);
20432
0
            for (ImGuiWindow* window : g.Windows)
20433
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20434
0
                    temp_buffer.push_back(window);
20435
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20436
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20437
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20438
0
            TreePop();
20439
0
        }
20440
20441
0
        TreePop();
20442
0
    }
20443
20444
    // DrawLists
20445
0
    int drawlist_count = 0;
20446
0
    for (ImGuiViewportP* viewport : g.Viewports)
20447
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20448
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20449
0
    {
20450
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20451
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20452
0
        for (ImGuiViewportP* viewport : g.Viewports)
20453
0
        {
20454
0
            bool viewport_has_drawlist = false;
20455
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20456
0
            {
20457
0
                if (!viewport_has_drawlist)
20458
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20459
0
                viewport_has_drawlist = true;
20460
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20461
0
            }
20462
0
        }
20463
0
        TreePop();
20464
0
    }
20465
20466
    // Viewports
20467
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20468
0
    {
20469
0
        cfg->HighlightMonitorIdx = -1;
20470
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20471
0
        SameLine();
20472
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20473
0
        if (open)
20474
0
        {
20475
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20476
0
            {
20477
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20478
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20479
0
                    i, mon.DpiScale * 100.0f,
20480
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20481
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20482
0
                if (IsItemHovered())
20483
0
                    cfg->HighlightMonitorIdx = i;
20484
0
            }
20485
0
            TreePop();
20486
0
        }
20487
20488
0
        SetNextItemOpen(true, ImGuiCond_Once);
20489
0
        if (TreeNode("Windows Minimap"))
20490
0
        {
20491
0
            RenderViewportsThumbnails();
20492
0
            TreePop();
20493
0
        }
20494
0
        cfg->HighlightViewportID = 0;
20495
20496
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20497
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20498
0
        {
20499
0
            static ImVector<ImGuiViewportP*> viewports;
20500
0
            viewports.resize(g.Viewports.Size);
20501
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20502
0
            if (viewports.Size > 1)
20503
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20504
0
            for (ImGuiViewportP* viewport : viewports)
20505
0
            {
20506
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20507
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20508
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20509
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20510
0
                if (IsItemHovered())
20511
0
                    cfg->HighlightViewportID = viewport->ID;
20512
0
            }
20513
0
            TreePop();
20514
0
        }
20515
20516
0
        for (ImGuiViewportP* viewport : g.Viewports)
20517
0
            DebugNodeViewport(viewport);
20518
0
        TreePop();
20519
0
    }
20520
20521
    // Details for Popups
20522
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20523
0
    {
20524
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20525
0
        {
20526
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20527
0
            ImGuiWindow* window = popup_data.Window;
20528
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20529
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20530
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20531
0
        }
20532
0
        TreePop();
20533
0
    }
20534
20535
    // Details for TabBars
20536
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20537
0
    {
20538
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20539
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20540
0
            {
20541
0
                PushID(tab_bar);
20542
0
                DebugNodeTabBar(tab_bar, "TabBar");
20543
0
                PopID();
20544
0
            }
20545
0
        TreePop();
20546
0
    }
20547
20548
    // Details for Tables
20549
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20550
0
    {
20551
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20552
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20553
0
                DebugNodeTable(table);
20554
0
        TreePop();
20555
0
    }
20556
20557
    // Details for Fonts
20558
0
    ImFontAtlas* atlas = g.IO.Fonts;
20559
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20560
0
    {
20561
0
        ShowFontAtlas(atlas);
20562
0
        TreePop();
20563
0
    }
20564
20565
    // Details for InputText
20566
0
    if (TreeNode("InputText"))
20567
0
    {
20568
0
        DebugNodeInputTextState(&g.InputTextState);
20569
0
        TreePop();
20570
0
    }
20571
20572
    // Details for TypingSelect
20573
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20574
0
    {
20575
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20576
0
        TreePop();
20577
0
    }
20578
20579
    // Details for Docking
20580
0
#ifdef IMGUI_HAS_DOCK
20581
0
    if (TreeNode("Docking"))
20582
0
    {
20583
0
        static bool root_nodes_only = true;
20584
0
        ImGuiDockContext* dc = &g.DockContext;
20585
0
        Checkbox("List root nodes", &root_nodes_only);
20586
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20587
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20588
0
        SameLine();
20589
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20590
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20591
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20592
0
                if (!root_nodes_only || node->IsRootNode())
20593
0
                    DebugNodeDockNode(node, "Node");
20594
0
        TreePop();
20595
0
    }
20596
0
#endif // #ifdef IMGUI_HAS_DOCK
20597
20598
    // Settings
20599
0
    if (TreeNode("Settings"))
20600
0
    {
20601
0
        if (SmallButton("Clear"))
20602
0
            ClearIniSettings();
20603
0
        SameLine();
20604
0
        if (SmallButton("Save to memory"))
20605
0
            SaveIniSettingsToMemory();
20606
0
        SameLine();
20607
0
        if (SmallButton("Save to disk"))
20608
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20609
0
        SameLine();
20610
0
        if (g.IO.IniFilename)
20611
0
            Text("\"%s\"", g.IO.IniFilename);
20612
0
        else
20613
0
            TextUnformatted("<NULL>");
20614
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20615
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20616
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20617
0
        {
20618
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20619
0
                BulletText("\"%s\"", handler.TypeName);
20620
0
            TreePop();
20621
0
        }
20622
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20623
0
        {
20624
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20625
0
                DebugNodeWindowSettings(settings);
20626
0
            TreePop();
20627
0
        }
20628
20629
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20630
0
        {
20631
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20632
0
                DebugNodeTableSettings(settings);
20633
0
            TreePop();
20634
0
        }
20635
20636
0
#ifdef IMGUI_HAS_DOCK
20637
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20638
0
        {
20639
0
            ImGuiDockContext* dc = &g.DockContext;
20640
0
            Text("In SettingsWindows:");
20641
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20642
0
                if (settings->DockId != 0)
20643
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20644
0
            Text("In SettingsNodes:");
20645
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20646
0
            {
20647
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20648
0
                const char* selected_tab_name = NULL;
20649
0
                if (settings->SelectedTabId)
20650
0
                {
20651
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20652
0
                        selected_tab_name = window->Name;
20653
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20654
0
                        selected_tab_name = window_settings->GetName();
20655
0
                }
20656
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20657
0
            }
20658
0
            TreePop();
20659
0
        }
20660
0
#endif // #ifdef IMGUI_HAS_DOCK
20661
20662
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20663
0
        {
20664
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20665
0
            TreePop();
20666
0
        }
20667
0
        TreePop();
20668
0
    }
20669
20670
    // Settings
20671
0
    if (TreeNode("Memory allocations"))
20672
0
    {
20673
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20674
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20675
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20676
0
        Text("Recent frames with allocations:");
20677
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20678
0
        for (int n = buf_size - 1; n >= 0; n--)
20679
0
        {
20680
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20681
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20682
0
        }
20683
0
        TreePop();
20684
0
    }
20685
20686
0
    if (TreeNode("Inputs"))
20687
0
    {
20688
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20689
0
        {
20690
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20691
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20692
0
            Indent();
20693
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20694
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20695
#else
20696
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20697
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20698
#endif
20699
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20700
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20701
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20702
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20703
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20704
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20705
0
            Unindent();
20706
0
        }
20707
20708
0
        Text("MOUSE STATE");
20709
0
        {
20710
0
            Indent();
20711
0
            if (IsMousePosValid())
20712
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20713
0
            else
20714
0
                Text("Mouse pos: <INVALID>");
20715
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20716
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20717
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20718
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20719
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20720
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20721
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20722
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20723
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20724
0
            Unindent();
20725
0
        }
20726
20727
0
        Text("MOUSE WHEELING");
20728
0
        {
20729
0
            Indent();
20730
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20731
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20732
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20733
0
            Unindent();
20734
0
        }
20735
20736
0
        Text("KEY OWNERS");
20737
0
        {
20738
0
            Indent();
20739
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20740
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20741
0
                {
20742
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20743
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
20744
0
                        continue;
20745
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20746
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20747
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20748
0
                }
20749
0
            EndChild();
20750
0
            Unindent();
20751
0
        }
20752
0
        Text("SHORTCUT ROUTING");
20753
0
        SameLine();
20754
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20755
0
        {
20756
0
            Indent();
20757
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20758
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20759
0
                {
20760
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20761
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20762
0
                    {
20763
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20764
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20765
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20766
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20767
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20768
0
                        {
20769
0
                            SameLine();
20770
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20771
0
                                g.DebugBreakInShortcutRouting = key_chord;
20772
0
                        }
20773
0
                        idx = routing_data->NextEntryIndex;
20774
0
                    }
20775
0
                }
20776
0
            EndChild();
20777
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20778
0
            Unindent();
20779
0
        }
20780
0
        TreePop();
20781
0
    }
20782
20783
0
    if (TreeNode("Internal state"))
20784
0
    {
20785
0
        Text("WINDOWING");
20786
0
        Indent();
20787
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20788
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20789
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20790
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20791
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20792
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20793
0
        Unindent();
20794
20795
0
        Text("ITEMS");
20796
0
        Indent();
20797
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20798
0
        DebugLocateItemOnHover(g.ActiveId);
20799
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20800
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20801
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20802
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20803
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20804
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20805
0
        Unindent();
20806
20807
0
        Text("NAV,FOCUS");
20808
0
        Indent();
20809
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20810
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20811
0
        DebugLocateItemOnHover(g.NavId);
20812
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20813
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20814
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20815
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20816
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20817
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20818
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20819
0
        Text("NavFocusRoute[] = ");
20820
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20821
0
        {
20822
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20823
0
            SameLine(0.0f, 0.0f);
20824
0
            Text("0x%08X/", focus_scope.ID);
20825
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20826
0
        }
20827
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20828
0
        Unindent();
20829
20830
0
        TreePop();
20831
0
    }
20832
20833
    // Overlay: Display windows Rectangles and Begin Order
20834
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20835
0
    {
20836
0
        for (ImGuiWindow* window : g.Windows)
20837
0
        {
20838
0
            if (!window->WasActive)
20839
0
                continue;
20840
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20841
0
            if (cfg->ShowWindowsRects)
20842
0
            {
20843
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20844
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20845
0
            }
20846
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20847
0
            {
20848
0
                char buf[32];
20849
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20850
0
                float font_size = GetFontSize();
20851
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20852
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20853
0
            }
20854
0
        }
20855
0
    }
20856
20857
    // Overlay: Display Tables Rectangles
20858
0
    if (cfg->ShowTablesRects)
20859
0
    {
20860
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20861
0
        {
20862
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20863
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20864
0
                continue;
20865
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20866
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20867
0
            {
20868
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20869
0
                {
20870
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20871
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20872
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20873
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20874
0
                }
20875
0
            }
20876
0
            else
20877
0
            {
20878
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20879
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20880
0
            }
20881
0
        }
20882
0
    }
20883
20884
0
#ifdef IMGUI_HAS_DOCK
20885
    // Overlay: Display Docking info
20886
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20887
0
    {
20888
0
        char buf[64] = "";
20889
0
        char* p = buf;
20890
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20891
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20892
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20893
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20894
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20895
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20896
0
        int depth = DockNodeGetDepth(node);
20897
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20898
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20899
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20900
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20901
0
    }
20902
0
#endif // #ifdef IMGUI_HAS_DOCK
20903
20904
0
    End();
20905
0
}
20906
20907
void ImGui::DebugBreakClearData()
20908
0
{
20909
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
20910
0
    ImGuiContext& g = *GImGui;
20911
0
    g.DebugBreakInWindow = 0;
20912
0
    g.DebugBreakInTable = 0;
20913
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
20914
0
}
20915
20916
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20917
0
{
20918
0
    if (!BeginItemTooltip())
20919
0
        return;
20920
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
20921
0
    Separator();
20922
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20923
0
    Separator();
20924
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20925
0
    EndTooltip();
20926
0
}
20927
20928
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20929
// In order to reduce interferences with the contents we are trying to debug into.
20930
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20931
0
{
20932
0
    ImGuiWindow* window = GetCurrentWindow();
20933
0
    if (window->SkipItems)
20934
0
        return false;
20935
20936
0
    ImGuiContext& g = *GImGui;
20937
0
    const ImGuiID id = window->GetID(label);
20938
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
20939
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20940
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20941
20942
0
    const ImRect bb(pos, pos + size);
20943
0
    ItemSize(size, 0.0f);
20944
0
    if (!ItemAdd(bb, id))
20945
0
        return false;
20946
20947
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
20948
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
20949
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
20950
0
    DebugBreakButtonTooltip(false, description_of_location);
20951
20952
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
20953
0
    ImVec4 hsv;
20954
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
20955
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
20956
20957
0
    RenderNavHighlight(bb, id);
20958
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
20959
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
20960
20961
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
20962
0
    return pressed;
20963
0
}
20964
20965
// [DEBUG] Display contents of Columns
20966
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20967
0
{
20968
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20969
0
        return;
20970
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20971
0
    for (ImGuiOldColumnData& column : columns->Columns)
20972
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20973
0
    TreePop();
20974
0
}
20975
20976
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20977
0
{
20978
0
    using namespace ImGui;
20979
0
    PushID(label);
20980
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20981
0
    Text("%s:", label);
20982
0
    if (!enabled)
20983
0
        BeginDisabled();
20984
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20985
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20986
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20987
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20988
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20989
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20990
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20991
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
20992
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20993
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20994
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20995
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20996
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20997
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20998
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20999
0
    if (!enabled)
21000
0
        EndDisabled();
21001
0
    PopStyleVar();
21002
0
    PopID();
21003
0
}
21004
21005
// [DEBUG] Display contents of ImDockNode
21006
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
21007
0
{
21008
0
    ImGuiContext& g = *GImGui;
21009
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
21010
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
21011
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21012
0
    bool open;
21013
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21014
0
    if (node->Windows.Size > 0)
21015
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21016
0
    else
21017
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21018
0
    if (!is_alive) { PopStyleColor(); }
21019
0
    if (is_active && IsItemHovered())
21020
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
21021
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
21022
0
    if (open)
21023
0
    {
21024
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
21025
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
21026
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
21027
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
21028
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
21029
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
21030
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
21031
0
        BulletText("Misc:%s%s%s%s%s%s%s",
21032
0
            node->IsDockSpace() ? " IsDockSpace" : "",
21033
0
            node->IsCentralNode() ? " IsCentralNode" : "",
21034
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
21035
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
21036
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
21037
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
21038
0
        {
21039
0
            if (BeginTable("flags", 4))
21040
0
            {
21041
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
21042
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
21043
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
21044
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
21045
0
                EndTable();
21046
0
            }
21047
0
            TreePop();
21048
0
        }
21049
0
        if (node->ParentNode)
21050
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
21051
0
        if (node->ChildNodes[0])
21052
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
21053
0
        if (node->ChildNodes[1])
21054
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
21055
0
        if (node->TabBar)
21056
0
            DebugNodeTabBar(node->TabBar, "TabBar");
21057
0
        DebugNodeWindowsList(&node->Windows, "Windows");
21058
21059
0
        TreePop();
21060
0
    }
21061
0
}
21062
21063
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21064
0
{
21065
0
    union { void* ptr; int integer; } tex_id_opaque;
21066
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21067
0
    if (sizeof(tex_id) >= sizeof(void*))
21068
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21069
0
    else
21070
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21071
0
}
21072
21073
// [DEBUG] Display contents of ImDrawList
21074
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
21075
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
21076
0
{
21077
0
    ImGuiContext& g = *GImGui;
21078
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21079
0
    int cmd_count = draw_list->CmdBuffer.Size;
21080
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
21081
0
        cmd_count--;
21082
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
21083
0
    if (draw_list == GetWindowDrawList())
21084
0
    {
21085
0
        SameLine();
21086
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
21087
0
        if (node_open)
21088
0
            TreePop();
21089
0
        return;
21090
0
    }
21091
21092
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
21093
0
    if (window && IsItemHovered() && fg_draw_list)
21094
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21095
0
    if (!node_open)
21096
0
        return;
21097
21098
0
    if (window && !window->WasActive)
21099
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
21100
21101
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
21102
0
    {
21103
0
        if (pcmd->UserCallback)
21104
0
        {
21105
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
21106
0
            continue;
21107
0
        }
21108
21109
0
        char texid_desc[20];
21110
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
21111
0
        char buf[300];
21112
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
21113
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
21114
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
21115
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
21116
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
21117
0
        if (!pcmd_node_open)
21118
0
            continue;
21119
21120
        // Calculate approximate coverage area (touched pixel count)
21121
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
21122
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
21123
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
21124
0
        float total_area = 0.0f;
21125
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
21126
0
        {
21127
0
            ImVec2 triangle[3];
21128
0
            for (int n = 0; n < 3; n++, idx_n++)
21129
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
21130
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
21131
0
        }
21132
21133
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
21134
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
21135
0
        Selectable(buf);
21136
0
        if (IsItemHovered() && fg_draw_list)
21137
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
21138
21139
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
21140
0
        ImGuiListClipper clipper;
21141
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
21142
0
        while (clipper.Step())
21143
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
21144
0
            {
21145
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
21146
0
                ImVec2 triangle[3];
21147
0
                for (int n = 0; n < 3; n++, idx_i++)
21148
0
                {
21149
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
21150
0
                    triangle[n] = v.pos;
21151
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
21152
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
21153
0
                }
21154
21155
0
                Selectable(buf, false);
21156
0
                if (fg_draw_list && IsItemHovered())
21157
0
                {
21158
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
21159
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21160
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
21161
0
                    fg_draw_list->Flags = backup_flags;
21162
0
                }
21163
0
            }
21164
0
        TreePop();
21165
0
    }
21166
0
    TreePop();
21167
0
}
21168
21169
// [DEBUG] Display mesh/aabb of a ImDrawCmd
21170
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
21171
0
{
21172
0
    IM_ASSERT(show_mesh || show_aabb);
21173
21174
    // Draw wire-frame version of all triangles
21175
0
    ImRect clip_rect = draw_cmd->ClipRect;
21176
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21177
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
21178
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21179
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
21180
0
    {
21181
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
21182
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
21183
21184
0
        ImVec2 triangle[3];
21185
0
        for (int n = 0; n < 3; n++, idx_n++)
21186
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
21187
0
        if (show_mesh)
21188
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
21189
0
    }
21190
    // Draw bounding boxes
21191
0
    if (show_aabb)
21192
0
    {
21193
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
21194
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
21195
0
    }
21196
0
    out_draw_list->Flags = backup_flags;
21197
0
}
21198
21199
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
21200
void ImGui::DebugNodeFont(ImFont* font)
21201
0
{
21202
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
21203
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
21204
0
    SameLine();
21205
0
    if (SmallButton("Set as default"))
21206
0
        GetIO().FontDefault = font;
21207
0
    if (!opened)
21208
0
        return;
21209
21210
    // Display preview text
21211
0
    PushFont(font);
21212
0
    Text("The quick brown fox jumps over the lazy dog");
21213
0
    PopFont();
21214
21215
    // Display details
21216
0
    SetNextItemWidth(GetFontSize() * 8);
21217
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
21218
0
    SameLine(); MetricsHelpMarker(
21219
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
21220
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
21221
0
        "You may oversample them to get some flexibility with scaling. "
21222
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
21223
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
21224
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
21225
0
    char c_str[5];
21226
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
21227
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
21228
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
21229
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
21230
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
21231
0
        if (font->ConfigData)
21232
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
21233
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
21234
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
21235
21236
    // Display all glyphs of the fonts in separate pages of 256 characters
21237
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
21238
0
    {
21239
0
        ImDrawList* draw_list = GetWindowDrawList();
21240
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
21241
0
        const float cell_size = font->FontSize * 1;
21242
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
21243
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
21244
0
        {
21245
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
21246
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
21247
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
21248
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
21249
0
            {
21250
0
                base += 4096 - 256;
21251
0
                continue;
21252
0
            }
21253
21254
0
            int count = 0;
21255
0
            for (unsigned int n = 0; n < 256; n++)
21256
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
21257
0
                    count++;
21258
0
            if (count <= 0)
21259
0
                continue;
21260
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
21261
0
                continue;
21262
21263
            // Draw a 16x16 grid of glyphs
21264
0
            ImVec2 base_pos = GetCursorScreenPos();
21265
0
            for (unsigned int n = 0; n < 256; n++)
21266
0
            {
21267
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
21268
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
21269
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
21270
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
21271
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
21272
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
21273
0
                if (!glyph)
21274
0
                    continue;
21275
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
21276
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
21277
0
                {
21278
0
                    DebugNodeFontGlyph(font, glyph);
21279
0
                    EndTooltip();
21280
0
                }
21281
0
            }
21282
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
21283
0
            TreePop();
21284
0
        }
21285
0
        TreePop();
21286
0
    }
21287
0
    TreePop();
21288
0
}
21289
21290
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
21291
0
{
21292
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
21293
0
    Separator();
21294
0
    Text("Visible: %d", glyph->Visible);
21295
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
21296
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
21297
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
21298
0
}
21299
21300
// [DEBUG] Display contents of ImGuiStorage
21301
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
21302
0
{
21303
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
21304
0
        return;
21305
0
    for (const ImGuiStoragePair& p : storage->Data)
21306
0
    {
21307
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
21308
0
        DebugLocateItemOnHover(p.key);
21309
0
    }
21310
0
    TreePop();
21311
0
}
21312
21313
// [DEBUG] Display contents of ImGuiTabBar
21314
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
21315
0
{
21316
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
21317
0
    char buf[256];
21318
0
    char* p = buf;
21319
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
21320
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
21321
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
21322
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
21323
0
    {
21324
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21325
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
21326
0
    }
21327
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
21328
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21329
0
    bool open = TreeNode(label, "%s", buf);
21330
0
    if (!is_active) { PopStyleColor(); }
21331
0
    if (is_active && IsItemHovered())
21332
0
    {
21333
0
        ImDrawList* draw_list = GetForegroundDrawList();
21334
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21335
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21336
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21337
0
    }
21338
0
    if (open)
21339
0
    {
21340
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21341
0
        {
21342
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21343
0
            PushID(tab);
21344
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21345
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21346
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21347
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21348
0
            PopID();
21349
0
        }
21350
0
        TreePop();
21351
0
    }
21352
0
}
21353
21354
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21355
0
{
21356
0
    ImGuiContext& g = *GImGui;
21357
0
    SetNextItemOpen(true, ImGuiCond_Once);
21358
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21359
0
    if (IsItemHovered())
21360
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21361
0
    if (open)
21362
0
    {
21363
0
        ImGuiWindowFlags flags = viewport->Flags;
21364
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21365
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21366
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21367
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21368
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21369
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21370
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21371
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21372
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21373
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21374
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21375
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21376
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21377
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21378
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21379
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21380
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21381
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21382
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21383
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21384
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21385
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21386
0
        TreePop();
21387
0
    }
21388
0
}
21389
21390
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21391
0
{
21392
0
    if (window == NULL)
21393
0
    {
21394
0
        BulletText("%s: NULL", label);
21395
0
        return;
21396
0
    }
21397
21398
0
    ImGuiContext& g = *GImGui;
21399
0
    const bool is_active = window->WasActive;
21400
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21401
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21402
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21403
0
    if (!is_active) { PopStyleColor(); }
21404
0
    if (IsItemHovered() && is_active)
21405
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21406
0
    if (!open)
21407
0
        return;
21408
21409
0
    if (window->MemoryCompacted)
21410
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21411
21412
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21413
0
        g.DebugBreakInWindow = window->ID;
21414
21415
0
    ImGuiWindowFlags flags = window->Flags;
21416
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21417
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21418
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21419
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21420
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21421
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21422
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21423
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21424
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21425
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21426
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21427
0
    {
21428
0
        ImRect r = window->NavRectRel[layer];
21429
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21430
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21431
0
        else
21432
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21433
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21434
0
    }
21435
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21436
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21437
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21438
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21439
21440
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21441
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21442
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21443
0
    if (window->DockNode || window->DockNodeAsHost)
21444
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21445
21446
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21447
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21448
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21449
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21450
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21451
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21452
0
    {
21453
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21454
0
            DebugNodeColumns(&columns);
21455
0
        TreePop();
21456
0
    }
21457
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21458
0
    TreePop();
21459
0
}
21460
21461
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21462
0
{
21463
0
    if (settings->WantDelete)
21464
0
        BeginDisabled();
21465
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21466
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21467
0
    if (settings->WantDelete)
21468
0
        EndDisabled();
21469
0
}
21470
21471
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21472
0
{
21473
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21474
0
        return;
21475
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21476
0
    {
21477
0
        PushID((*windows)[i]);
21478
0
        DebugNodeWindow((*windows)[i], "Window");
21479
0
        PopID();
21480
0
    }
21481
0
    TreePop();
21482
0
}
21483
21484
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21485
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21486
0
{
21487
0
    for (int i = 0; i < windows_size; i++)
21488
0
    {
21489
0
        ImGuiWindow* window = windows[i];
21490
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21491
0
            continue;
21492
0
        char buf[20];
21493
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21494
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21495
0
        DebugNodeWindow(window, buf);
21496
0
        Indent();
21497
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21498
0
        Unindent();
21499
0
    }
21500
0
}
21501
21502
//-----------------------------------------------------------------------------
21503
// [SECTION] DEBUG LOG WINDOW
21504
//-----------------------------------------------------------------------------
21505
21506
void ImGui::DebugLog(const char* fmt, ...)
21507
0
{
21508
0
    va_list args;
21509
0
    va_start(args, fmt);
21510
0
    DebugLogV(fmt, args);
21511
0
    va_end(args);
21512
0
}
21513
21514
void ImGui::DebugLogV(const char* fmt, va_list args)
21515
0
{
21516
0
    ImGuiContext& g = *GImGui;
21517
0
    const int old_size = g.DebugLogBuf.size();
21518
0
    if (g.ContextName[0] != 0)
21519
0
        g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
21520
0
    else
21521
0
        g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21522
0
    g.DebugLogBuf.appendfv(fmt, args);
21523
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21524
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21525
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21526
#ifdef IMGUI_ENABLE_TEST_ENGINE
21527
    // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
21528
    const int new_size = g.DebugLogBuf.size();
21529
    const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
21530
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21531
        IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
21532
#endif
21533
0
}
21534
21535
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21536
static void SameLineOrWrap(const ImVec2& size)
21537
0
{
21538
0
    ImGuiContext& g = *GImGui;
21539
0
    ImGuiWindow* window = g.CurrentWindow;
21540
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21541
0
    if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21542
0
        ImGui::SameLine();
21543
0
}
21544
21545
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21546
0
{
21547
0
    ImGuiContext& g = *GImGui;
21548
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21549
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21550
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21551
0
    {
21552
0
        g.DebugLogAutoDisableFrames = 2;
21553
0
        g.DebugLogAutoDisableFlags |= flags;
21554
0
    }
21555
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21556
0
}
21557
21558
void ImGui::ShowDebugLogWindow(bool* p_open)
21559
0
{
21560
0
    ImGuiContext& g = *GImGui;
21561
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21562
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21563
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21564
0
    {
21565
0
        End();
21566
0
        return;
21567
0
    }
21568
21569
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21570
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21571
0
    SetItemTooltip("(except InputRouting which is spammy)");
21572
21573
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21574
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21575
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21576
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21577
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21578
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21579
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21580
    //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21581
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21582
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21583
21584
0
    if (SmallButton("Clear"))
21585
0
    {
21586
0
        g.DebugLogBuf.clear();
21587
0
        g.DebugLogIndex.clear();
21588
0
    }
21589
0
    SameLine();
21590
0
    if (SmallButton("Copy"))
21591
0
        SetClipboardText(g.DebugLogBuf.c_str());
21592
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21593
21594
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21595
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21596
21597
0
    ImGuiListClipper clipper;
21598
0
    clipper.Begin(g.DebugLogIndex.size());
21599
0
    while (clipper.Step())
21600
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21601
0
            DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
21602
0
    g.DebugLogFlags = backup_log_flags;
21603
0
    if (GetScrollY() >= GetScrollMaxY())
21604
0
        SetScrollHereY(1.0f);
21605
0
    EndChild();
21606
21607
0
    End();
21608
0
}
21609
21610
// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
21611
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
21612
0
{
21613
0
    TextUnformatted(line_begin, line_end);
21614
0
    if (!IsItemHovered())
21615
0
        return;
21616
0
    ImGuiContext& g = *GImGui;
21617
0
    ImRect text_rect = g.LastItemData.Rect;
21618
0
    for (const char* p = line_begin; p <= line_end - 10; p++)
21619
0
    {
21620
0
        ImGuiID id = 0;
21621
0
        if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21622
0
            continue;
21623
0
        ImVec2 p0 = CalcTextSize(line_begin, p);
21624
0
        ImVec2 p1 = CalcTextSize(p, p + 10);
21625
0
        g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21626
0
        if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21627
0
            DebugLocateItemOnHover(id);
21628
0
        p += 10;
21629
0
    }
21630
0
}
21631
21632
//-----------------------------------------------------------------------------
21633
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21634
//-----------------------------------------------------------------------------
21635
21636
// Draw a small cross at current CursorPos in current window's DrawList
21637
void ImGui::DebugDrawCursorPos(ImU32 col)
21638
0
{
21639
0
    ImGuiContext& g = *GImGui;
21640
0
    ImGuiWindow* window = g.CurrentWindow;
21641
0
    ImVec2 pos = window->DC.CursorPos;
21642
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21643
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21644
0
}
21645
21646
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21647
void ImGui::DebugDrawLineExtents(ImU32 col)
21648
0
{
21649
0
    ImGuiContext& g = *GImGui;
21650
0
    ImGuiWindow* window = g.CurrentWindow;
21651
0
    float curr_x = window->DC.CursorPos.x;
21652
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21653
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21654
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21655
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21656
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21657
0
}
21658
21659
// Draw last item rect in ForegroundDrawList (so it is always visible)
21660
void ImGui::DebugDrawItemRect(ImU32 col)
21661
0
{
21662
0
    ImGuiContext& g = *GImGui;
21663
0
    ImGuiWindow* window = g.CurrentWindow;
21664
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21665
0
}
21666
21667
// [DEBUG] Locate item position/rectangle given an ID.
21668
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21669
21670
void ImGui::DebugLocateItem(ImGuiID target_id)
21671
0
{
21672
0
    ImGuiContext& g = *GImGui;
21673
0
    g.DebugLocateId = target_id;
21674
0
    g.DebugLocateFrames = 2;
21675
0
    g.DebugBreakInLocateId = false;
21676
0
}
21677
21678
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21679
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21680
0
{
21681
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21682
0
        return;
21683
0
    ImGuiContext& g = *GImGui;
21684
0
    DebugLocateItem(target_id);
21685
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21686
21687
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21688
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21689
0
    {
21690
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21691
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21692
0
            g.DebugBreakInLocateId = true;
21693
0
    }
21694
0
}
21695
21696
void ImGui::DebugLocateItemResolveWithLastItem()
21697
0
{
21698
0
    ImGuiContext& g = *GImGui;
21699
21700
    // [DEBUG] Debug break requested by user
21701
0
    if (g.DebugBreakInLocateId)
21702
0
        IM_DEBUG_BREAK();
21703
21704
0
    ImGuiLastItemData item_data = g.LastItemData;
21705
0
    g.DebugLocateId = 0;
21706
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21707
0
    ImRect r = item_data.Rect;
21708
0
    r.Expand(3.0f);
21709
0
    ImVec2 p1 = g.IO.MousePos;
21710
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21711
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21712
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21713
0
}
21714
21715
void ImGui::DebugStartItemPicker()
21716
0
{
21717
0
    ImGuiContext& g = *GImGui;
21718
0
    g.DebugItemPickerActive = true;
21719
0
}
21720
21721
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21722
void ImGui::UpdateDebugToolItemPicker()
21723
138k
{
21724
138k
    ImGuiContext& g = *GImGui;
21725
138k
    g.DebugItemPickerBreakId = 0;
21726
138k
    if (!g.DebugItemPickerActive)
21727
138k
        return;
21728
21729
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21730
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21731
0
    if (IsKeyPressed(ImGuiKey_Escape))
21732
0
        g.DebugItemPickerActive = false;
21733
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21734
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21735
0
    {
21736
0
        g.DebugItemPickerBreakId = hovered_id;
21737
0
        g.DebugItemPickerActive = false;
21738
0
    }
21739
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21740
0
        if (change_mapping && IsMouseClicked(mouse_button))
21741
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21742
0
    SetNextWindowBgAlpha(0.70f);
21743
0
    if (!BeginTooltip())
21744
0
        return;
21745
0
    Text("HoveredId: 0x%08X", hovered_id);
21746
0
    Text("Press ESC to abort picking.");
21747
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21748
0
    if (change_mapping)
21749
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21750
0
    else
21751
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21752
0
    EndTooltip();
21753
0
}
21754
21755
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21756
void ImGui::UpdateDebugToolStackQueries()
21757
138k
{
21758
138k
    ImGuiContext& g = *GImGui;
21759
138k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21760
21761
    // Clear hook when id stack tool is not visible
21762
138k
    g.DebugHookIdInfo = 0;
21763
138k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21764
138k
        return;
21765
21766
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21767
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21768
9
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21769
9
    if (tool->QueryId != query_id)
21770
0
    {
21771
0
        tool->QueryId = query_id;
21772
0
        tool->StackLevel = -1;
21773
0
        tool->Results.resize(0);
21774
0
    }
21775
9
    if (query_id == 0)
21776
9
        return;
21777
21778
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21779
0
    int stack_level = tool->StackLevel;
21780
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21781
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21782
0
            tool->StackLevel++;
21783
21784
    // Update hook
21785
0
    stack_level = tool->StackLevel;
21786
0
    if (stack_level == -1)
21787
0
        g.DebugHookIdInfo = query_id;
21788
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21789
0
    {
21790
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21791
0
        tool->Results[stack_level].QueryFrameCount++;
21792
0
    }
21793
0
}
21794
21795
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21796
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21797
0
{
21798
0
    ImGuiContext& g = *GImGui;
21799
0
    ImGuiWindow* window = g.CurrentWindow;
21800
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21801
21802
    // Step 0: stack query
21803
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21804
0
    if (tool->StackLevel == -1)
21805
0
    {
21806
0
        tool->StackLevel++;
21807
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21808
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21809
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21810
0
        return;
21811
0
    }
21812
21813
    // Step 1+: query for individual level
21814
0
    IM_ASSERT(tool->StackLevel >= 0);
21815
0
    if (tool->StackLevel != window->IDStack.Size)
21816
0
        return;
21817
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21818
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21819
21820
0
    switch (data_type)
21821
0
    {
21822
0
    case ImGuiDataType_S32:
21823
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21824
0
        break;
21825
0
    case ImGuiDataType_String:
21826
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21827
0
        break;
21828
0
    case ImGuiDataType_Pointer:
21829
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21830
0
        break;
21831
0
    case ImGuiDataType_ID:
21832
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21833
0
            return;
21834
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21835
0
        break;
21836
0
    default:
21837
0
        IM_ASSERT(0);
21838
0
    }
21839
0
    info->QuerySuccess = true;
21840
0
    info->DataType = data_type;
21841
0
}
21842
21843
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21844
0
{
21845
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21846
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21847
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21848
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21849
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21850
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21851
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21852
0
        return (*buf = 0);
21853
#ifdef IMGUI_ENABLE_TEST_ENGINE
21854
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
21855
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21856
#endif
21857
0
    return ImFormatString(buf, buf_size, "???");
21858
0
}
21859
21860
// ID Stack Tool: Display UI
21861
void ImGui::ShowIDStackToolWindow(bool* p_open)
21862
0
{
21863
0
    ImGuiContext& g = *GImGui;
21864
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21865
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
21866
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21867
0
    {
21868
0
        End();
21869
0
        return;
21870
0
    }
21871
21872
    // Display hovered/active status
21873
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21874
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21875
0
    const ImGuiID active_id = g.ActiveId;
21876
#ifdef IMGUI_ENABLE_TEST_ENGINE
21877
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21878
#else
21879
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
21880
0
#endif
21881
0
    SameLine();
21882
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21883
21884
    // CTRL+C to copy path
21885
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21886
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21887
0
    SameLine();
21888
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21889
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
21890
0
    {
21891
0
        tool->CopyToClipboardLastTime = (float)g.Time;
21892
0
        char* p = g.TempBuffer.Data;
21893
0
        char* p_end = p + g.TempBuffer.Size;
21894
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21895
0
        {
21896
0
            *p++ = '/';
21897
0
            char level_desc[256];
21898
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21899
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21900
0
            {
21901
0
                if (level_desc[n] == '/')
21902
0
                    *p++ = '\\';
21903
0
                *p++ = level_desc[n];
21904
0
            }
21905
0
        }
21906
0
        *p = '\0';
21907
0
        SetClipboardText(g.TempBuffer.Data);
21908
0
    }
21909
21910
    // Display decorated stack
21911
0
    tool->LastActiveFrame = g.FrameCount;
21912
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21913
0
    {
21914
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
21915
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21916
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21917
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21918
0
        TableHeadersRow();
21919
0
        for (int n = 0; n < tool->Results.Size; n++)
21920
0
        {
21921
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21922
0
            TableNextColumn();
21923
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21924
0
            TableNextColumn();
21925
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21926
0
            TextUnformatted(g.TempBuffer.Data);
21927
0
            TableNextColumn();
21928
0
            Text("0x%08X", info->ID);
21929
0
            if (n == tool->Results.Size - 1)
21930
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21931
0
        }
21932
0
        EndTable();
21933
0
    }
21934
0
    End();
21935
0
}
21936
21937
#else
21938
21939
void ImGui::ShowMetricsWindow(bool*) {}
21940
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21941
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21942
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21943
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21944
void ImGui::DebugNodeFont(ImFont*) {}
21945
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21946
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21947
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21948
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21949
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21950
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21951
21952
void ImGui::DebugLog(const char*, ...) {}
21953
void ImGui::DebugLogV(const char*, va_list) {}
21954
void ImGui::ShowDebugLogWindow(bool*) {}
21955
void ImGui::ShowIDStackToolWindow(bool*) {}
21956
void ImGui::DebugStartItemPicker() {}
21957
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21958
21959
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21960
21961
//-----------------------------------------------------------------------------
21962
21963
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21964
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21965
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21966
#include "imgui_user.inl"
21967
#endif
21968
21969
//-----------------------------------------------------------------------------
21970
21971
#endif // #ifndef IMGUI_DISABLE